> This is part 1 of 3 of the full documentation (pages 1–100 of 241).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.pyck.cloud/llms-full.txt/1
> Page index: https://docs.pyck.cloud/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pyck.cloud/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Welcome

Welcome to the pyck documentation! Here you'll find an overview as well as detailed explanations all around the warehouse management revolution.

If you have any questions or comments, please feel free to drop a note at <hello@pyck.ai>

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Basics</strong></td><td>Learn the basic concepts behind pyck</td><td></td><td></td><td><a href="/basics/concepts">Concepts</a></td></tr><tr><td><strong>Development</strong></td><td>Developer resources and guides</td><td></td><td></td><td><a href="/development/architecture">Architecture</a></td></tr><tr><td><strong>GraphQL API</strong></td><td>Explore the GraphQL API</td><td></td><td></td><td><a href="/graphql-api/getting-started">Getting Started</a></td></tr></tbody></table>


# Concepts

Basic Concepts

This page introduces the fundamental concepts of the pyck framework.

## Tenant

In pyck's multi-tenant architecture, a tenant is an isolated customer account that contains all their data. Think of it like an apartment building - each tenant has their own space (apartment) that's completely separate from others, even though they share the same building (software infrastructure). Each tenant can have multiple root-level repositories (warehouses), allowing a single company to manage operations across multiple facilities while keeping data isolated from other companies. This enables pyck to serve many customers on the same platform securely.

## Repositories

Repositories are the fundamental building blocks of pyck - any container that can hold goods is a repository. Unlike traditional WMS with fixed location types, pyck lets you create repositories for anything: warehouses, zones, shelves, bins, pallets, trolleys, or even forklifts. They form hierarchical structures where any repository can contain other repositories, creating your warehouse layout through parent-child relationships.

#### Types of Repositories

pyck features two types of repositories:

* **Static Repository:** Fixed in place, such as shelves or zones. These cannot be moved.
* **Dynamic Repository:** Movable and can be repositioned using RepositoryMovements.

Additionally, repositories can be categorized as real or virtual:

* **Real Repositories:** Physically store and track goods with full stock validation.
* **Virtual Repositories:** Special repositories that can "create stock out of nowhere" - they bypass stock validation checks. This is essential at warehouse boundaries where you need to introduce new items (receiving) or remove them (shipping). Common virtual repositories include:
  * **Receiving**: "Incoming Goods" or specific supplier repositories like "Apple Deliveries"
  * **Shipping**: "Customer Orders" or individual customer repositories
  * **Losses**: "Damaged", "Stolen", "Missing", "Internal Use"
  * **Adjustments**: "Inventory Correction"

The granularity of virtual repositories depends on your tracking needs - you might use one general "Incoming" repository or create dozens of supplier-specific ones for detailed tracking.

#### Repository Structure and Layout

Repositories can be nested within each other, forming the warehouse layout. For example, the "Warehouse Berlin" repository includes Zones A and B, along with inbound and outbound zones. Zone A is a sub-repository of "Warehouse Berlin."

## Movements

Movements are the core operational unit in pyck - they represent orders or tasks to relocate inventory between repositories. Unlike traditional systems that simply update database records, movements are executable instructions for workers or machines. Every inventory transfer, whether moving a single item or an entire pallet, is tracked as a movement. This creates a complete audit trail and enables time-travel queries to see inventory state at any point in history. Movements validate stock availability when created (except when sourcing from virtual repositories), ensuring operational feasibility.

pyck supports two types of movements:

1. **Item Movement**
2. **Repository Movement**

Repository movements are exclusive to dynamic repositories. When a movement is created, whether it's an item or repository movement, the system verifies order fulfillment by checking if there's sufficient stock available in the outgoing repository to carry out the transfer.

## Movement Collections

Movement collections group multiple movements into an ordered sequence - think of them as intelligent task lists. While traditional pick lists only handle item picking, collection movements can orchestrate complex operations mixing item movements (pick 10 units) with repository movements (move entire pallet). They're powerful because they can represent complete workflows like "take forklift to aisle 3, pick up pallet, move to staging, add items, deliver to dock." This flexibility enables optimization of worker routes and equipment usage across diverse warehouse operations.

For example, if we need 10 iPhones in the outbound zone, a movement collection might include:

* Pick 5 iPhones from Box 3 on Shelf 5 and load them onto your trolley.
* Pick another 5 iPhones from Box 14 on Shelf 6 and load them onto your trolley.
* Move the trolley to the outbound zone.
* Move 10 iPhones from your trolley to the table in the outbound zone.

The crucial point here is that when creating movements in a collection, the system performs forward-looking stock validation across the entire sequence. It knows that after executing the first two movements, there will be 10 iPhones on the trolley, making the fourth movement plausible. This is why collections are powerful - they validate the entire chain of operations, not just individual movements in isolation. If you tried to create the fourth movement alone (without the collection context), it would fail because the trolley currently has no iPhones.

If goods are moved from a virtual repository, stock levels are not validated in that repository. Virtual repositories facilitate the transfer of goods in and out of the warehouse.

## DataTypes

In pyck, each entity—such as customers, items, or suppliers—can store additional data in a JSON field called "data". To ensure this data is structured and validated, we use DataTypes, which are essentially JSON Schemas. Any data submitted through our API validates against these schemas and ensures data integrity.


# Mapping of pyck Terms

Common warehouse management terms and their pyck equivalents

Audience: Logistics Manager

This dictionary maps traditional warehouse management system (WMS) terminology to pyck's innovative naming conventions. Understanding these mappings will help you navigate pyck's unique approach to warehouse management.

## Warehouse Management Terms

### Storage & Locations

#### **Warehouse** → `Repository (root level)`

A warehouse is a large building where goods are stored before distribution. It's the main storage hub in a supply chain - like a giant organized garage for products. Warehouses have loading docks, storage areas, and equipment like forklifts. In pyck, warehouses are simply root-level repositories (no parent) in your tenant. You name them based on your needs ("Main Warehouse", "DC-East", "Building A") and use custom dataTypes to add attributes like address, capacity, or operating hours.

#### **Zone** → `Repository`

Zones are logical areas within a warehouse dedicated to specific activities or product types. Common zones include receiving (truck unloading), storage (bulk areas), picking (order assembly), packing (boxing), and shipping (order departure). Some warehouses have specialized zones like cold storage or hazardous materials. In pyck, zones are repositories nested within your warehouse repository. You might create "Receiving Zone", "Cold Storage", or "Fast Movers" - the structure and naming is entirely flexible based on your operations.

#### **Location/Bin** → `Repository`

A location or bin is a specific spot where items are stored - like a designated parking space for products. Each has a unique identifier (e.g., "A-12-3" for Aisle A, Rack 12, Level 3) enabling quick item retrieval. Good location management is crucial - imagine finding a book in a library without a catalog. In pyck, locations are repositories nested within zones or shelves. The hierarchical flexibility means you can model your exact warehouse layout, whether simple (warehouse → locations) or complex (warehouse → zone → aisle → rack → shelf → bin).

#### **Pallet** → `Repository (dynamic)`

A pallet is a flat transport structure (usually 48"×40" wood or plastic) that enables efficient movement with forklifts. Pallets turn individual boxes into single manageable units for bulk storage and shipping. Think of them as movable floors that can hold dozens of cases. In pyck, pallets are dynamic repositories that can contain items and move between locations. You might name them with existing IDs ("PAL-001") or generate new ones. Being repositories, pallets maintain their contents while moving through the warehouse.

### Inventory & Items

#### **SKU (Stock Keeping Unit)** → `InventoryItem.sku`

A SKU is a unique code for each distinct product and variant. A red t-shirt size M might be "TS-RED-M" while size L is "TS-RED-L". SKUs are like social security numbers for products - the foundation of inventory tracking. Every warehouse operation references SKUs: receiving ("100 units of SKU-X arrived"), picking ("get 2 of SKU-Y"), and shipping. Without SKUs, managing thousands of products would be chaos. In pyck, SKU is the only required field for InventoryItems - everything else is flexible.

#### **Inventory/Stock** → `Stock`

Inventory refers to product quantities in the warehouse, tracked at multiple levels: total quantity (what you have), available (what can be sold), and reserved (already allocated). It's like a bank account - you need total balance, available balance, and pending transactions. Accurate tracking prevents overselling and guides reordering. In pyck, Stock records provide real-time quantities AND complete history across all repositories. You can query "how much of SKU-X was in location Y last Tuesday" - powerful for analysis and auditing.

#### **Lot/Batch** → `InventoryItem.data`

Lot or batch numbers group products manufactured together, essential for traceability and recalls. If contamination is found in pharmaceutical lot #12345, you can quickly isolate affected units. Food uses lots to track expiration - "lot A expires March 2024". This tracking is mandatory in regulated industries and valuable everywhere for quality control. In pyck, lots are stored in flexible custom data fields, allowing different lot strategies per product type or supplier requirement.

#### **Expiry Date** → `InventoryItem.data`

Expiry dates indicate when products become unsuitable for sale. Critical for food, pharmaceuticals, and chemicals, they drive FIFO (First In, First Out) or FEFO (First Expired, First Out) strategies. Systems alert when products approach expiry, enabling markdowns or donations. Shipping expired goods risks returns, fines, or lawsuits. In pyck, expiry dates live in the flexible data JSON field, enabling custom alerts and queries based on your specific requirements and regulations.

#### **Barcode/Serial Number** → `InventoryItem.data`

Barcodes identify product types while serial numbers track individual units. Scanning eliminates errors - imagine typing 1000 codes daily versus scanning in seconds. Modern warehouses use various technologies: 1D barcodes (traditional lines), 2D codes (QR), or RFID (radio frequency). In pyck, SKU is the only required identifier. All others - UPC, EAN, serial numbers, RFID tags - are stored in custom data fields. Define your dataType schema to match your scanning infrastructure and partner requirements.

### Core Operations

#### **Receiving** → `ReceivingInbound`

Receiving is the warehouse's "intake department" - accepting deliveries from suppliers. It involves unloading trucks, verifying quantities against purchase orders, quality inspection, and system recording. Poor receiving creates cascading errors throughout operations. Modern receiving captures photos, lot numbers, expiry dates, and damage documentation. In pyck, ReceivingInbound entities track arrivals. Items move from virtual "supplier" repositories into your physical warehouse, maintaining complete documentation of what arrived when and from whom.

#### **Putaway** → `Movement`

Putaway moves received goods from docks to storage locations. It's strategic - fast-movers go near picking areas, heavy items on lower shelves, chemicals separate from food. Like organizing a kitchen, frequently used items go in accessible places. Efficient putaway reduces future picking time and prevents damage. In pyck, putaway is a movement from receiving area to storage repository. The system can suggest optimal locations based on product velocity, available space, and warehouse rules you define.

#### **Pick List** → `Collection Movement`

A pick list is a document that tells warehouse workers which items to collect for orders. It's like a shopping list optimized for efficiency - items are typically ordered by location to minimize walking distance. A picker might handle multiple orders at once (batch picking) or focus on one order (discrete picking). Modern pick lists might be displayed on handheld devices with optimal routes highlighted. In pyck, Collection Movements go beyond traditional pick lists by orchestrating both item picks and equipment movements in sequence.

#### **Picking** → `Movement`

Picking retrieves items from storage to fulfill orders - often 55% of warehouse operating costs. Methods vary: single-order (one at a time), batch (multiple orders together), zone (pickers in assigned areas), or wave (grouped releases). Optimization is crucial - smart routing reduces travel time by 50%. In pyck, picking is movements from storage to staging/packing areas. Collection movements enable sophisticated strategies like batch picking with optimal routing across multiple orders and zones.

#### **Wave Picking** → `Collection Movement`

Wave picking releases orders in coordinated groups rather than continuously. Like bus schedules, orders accumulate and depart together. Waves align with shipping schedules ("2 PM truck"), delivery routes, or shift patterns. This batching improves efficiency through better resource allocation and reduced congestion. In pyck, waves are collection movements orchestrating multiple picks and equipment movements. You might create waves for "Morning Route", "Express Shipments", or "Zone A Replenishment".

#### **Transfer/Transport** → `Movement`

Transfers are the relocation of inventory between locations within a warehouse or between warehouses. This could be moving items from bulk storage to picking locations (replenishment), consolidating partial pallets, or shipping to another facility. Think of it like reorganizing your closet - moving winter clothes to the attic in summer. Transfers must be tracked precisely to maintain accurate inventory. In pyck, all transfers are movements - executable instructions for workers or automated systems.

#### **Replenishment** → `Movement workflow`

Replenishment refills picking locations from bulk storage before they empty. Like restocking store shelves from the backroom, it's proactive to prevent stockouts. Systems calculate timing based on pick frequency, current levels, and incoming orders. Poor replenishment kills productivity when pickers find empty locations. In pyck, replenishment workflows create movements between repositories. Smart systems trigger replenishment during quiet periods or combine with other movements for efficiency.

#### **Cross-docking** → `Movement`

Cross-docking bypasses storage - products flow directly from receiving to shipping. Like a relay race where the baton never stops, it reduces handling, storage costs, and delivery time. Common for perishables, high-volume retail, and hub-and-spoke distribution. Requires precise coordination - incoming and outgoing schedules must align. In pyck, cross-dock operations are movements from receiving virtual repository directly to shipping virtual repository, with minimal time in physical warehouse space.

#### **Shipping/Dispatch** → `Movement`

Shipping is the warehouse "departure gate" where orders leave for customers. It involves order staging, truck loading (first stop loads last), documentation, and carrier integration. Everything must be verified before goods leave your control. Modern shipping includes real-time tracking and proof of delivery. In pyck, shipping moves items to virtual repositories representing customers or carriers ("Customer-ABC", "FedEx-Truck-123"). This maintains the movement record while removing items from physical inventory.

#### **Cycle Count** → `Stock verification workflow`

Cycle counting verifies inventory accuracy through regular partial counts rather than disruptive annual counts. Like checking your bank balance frequently instead of waiting for year-end. Workers count specific locations/SKUs daily, comparing physical to system records. Discrepancies trigger investigation - theft, damage, or data error? Regular counts maintain 99%+ accuracy. In pyck, cycle count workflows compare physical counts to Stock records, creating adjustment movements for discrepancies with reason codes.

#### **WMS** → `pyck framework`

A Warehouse Management System (WMS) is software controlling warehouse operations - the facility's "brain". It tracks inventory, directs workers, optimizes storage, and integrates with other systems. Good WMS improves accuracy to 99.9%, reduces labor 30%, and increases storage utilization 20%. pyck is NOT a WMS but a framework for building lean WMS stacks. With pyck's flexible repository and movement architecture, you can create industry-specific solutions for fashion, e-commerce, pharmaceuticals, or any vertical relatively easily.

## Common Operations Mapping

| Traditional WMS Operation | pyck Implementation                                                    |
| ------------------------- | ---------------------------------------------------------------------- |
| Create putaway task       | Create movement from receiving to storage repository                   |
| Generate pick list        | Create collection movement with ordered tasks                          |
| Transfer inventory        | Create movement between repositories                                   |
| Receive goods             | Create ReceivingInbound and movements from virtual supplier repository |
| Ship order                | Create movements to virtual customer repository                        |
| Move pallet               | Create repository movement changing parent                             |
| Batch pick orders         | Create collection movement with items from multiple orders             |
| Cycle count               | Run verification workflow, create adjustment movements                 |
| Cross-dock receipt        | Create movement from supplier virtual to customer virtual repository   |
| Replenish pick face       | Create movement from bulk to pick repository                           |
| Adjust inventory          | Create movement from/to virtual "adjustment" repository                |
| Quarantine items          | Move to "quarantine" repository with hold reason                       |
| Consolidate pallets       | Create movements to merge items onto single pallet                     |
| Split case                | Create movements dividing case quantity to multiple locations          |

Understanding these mappings enables you to leverage pyck's powerful framework for building exactly the warehouse management solution your operation needs.


# Workflows

Audience: Logistics Manager

## What Are Workflows?

Workflows in pyck are automated processes that help customize and control warehouse operations. Think of workflows as a series of predefined steps that automatically execute when certain events happen in your warehouse.

## How Workflows Work

1. **Event Triggers**: Workflows start when specific events occur in your warehouse system. For example:
   * A new order arrives
   * Inventory falls below a threshold
   * A shipment is received
   * A picking task is completed
2. **Automated Actions**: Once triggered, workflows follow a predefined sequence of activities without requiring manual intervention.
3. **Customization**: Each warehouse can have its own set of workflows tailored to its specific processes and requirements.

## Benefits of Using Workflows

* **Consistency**: Ensure warehouse processes follow the same steps every time
* **Efficiency**: Automate repetitive tasks to save time and reduce errors
* **Adaptability**: Easily modify your warehouse processes without changing the core system
* **Visibility**: Track and monitor process execution across your facility
* **Durability**: Workflows continue running even if there are system failures
* **Reliability**: Tasks are automatically retried if they fail, ensuring completion

## Common Workflow Examples

* **Receiving Process**: Automatically update inventory when goods arrive and notify relevant departments
* **Order Fulfillment**: Guide picking, packing, and shipping activities in the most efficient sequence
* **Inventory Management**: Trigger reordering when stock levels drop below defined thresholds
* **Quality Control**: Route items through inspection processes based on predefined rules

## Dynamic App Behavior

One of the most powerful features of pyck workflows is their ability to change the behavior of mobile apps and devices used in your warehouse. This means:

* **Adaptive User Interfaces**: Workflows can modify what screens and options appear on warehouse devices
* **Context-Aware Instructions**: Workers receive different instructions based on the specific circumstances
* **Real-Time Updates**: Apps can adapt immediately to changing conditions in the warehouse
* **Custom Process Flows**: Create unique step-by-step guides for different products, customers, or situations

For example, a picking workflow could change a mobile app to show different picking instructions based on the item type, storage location, or even the experience level of the warehouse worker. The technical details of how this works will be covered in separate documentation, but the important thing to understand is that workflows give you the power to customize app behavior through your business processes.

## How to Implement Workflows

pyck uses Business Process Model and Notation (BPMN) as a common language between logistics managers and technical teams. This visual approach allows you to:

1. **Design processes visually**: Create flowcharts showing the steps in your warehouse operations
2. **Communicate effectively**: Share your process requirements with technical teams using standard notation
3. **Review implementations**: Ensure the technical implementation matches your operational needs

AI coding agents generate the workflow code from your BPMN models, on your own isolated codebase. Developers review and quality-assure the generated code instead of writing it by hand, so a change to a process lands in hours or days. The code runs on Temporal.io, a workflow engine that keeps workflows reliable and durable, and is written primarily in Go using the pyck Go SDK.

## Reference Implementation

For a practical example of how workflows are implemented in pyck, developers reviewing the generated code can refer to our reference implementation at: <https://github.com/pyck-ai/pyck-customer-template>

This template provides examples of common warehouse workflows that can be customized to your specific requirements.

## Activating or Deactivating a Workflow

### What is the `Active` flag?

* **Purpose:** A simple on/off switch to enable or disable a workflow.
* **Where to set it:** When you create or update a workflow definition include the `active` field.

#### How it works?

* When `active` is `true`, the system will consider this workflow for triggering.
* When `active` is `false`, the workflow remains in the catalog but will never be launched, even if an event matches its filter.

## Filtering Events with `FilterRule`

### What is the `FilterRule` ?

* **Purpose:** A conditional expression that decides whether an incoming event should trigger the workflow.
* **Syntax:** Uses FEEL (Friendly Enough Expression Language), which supports logical operators, comparisons, and built-in functions.

### How to write a rule

1. Reference event fields by name: if your event data includes a field `name`, use `name` in the expression.
2. Built-in functions: such as `starts with(text, prefix)`, `contains(text, substring)`, numeric comparisons (`>`, `<`, `=`, etc.).
3. Logical operators: combine conditions with `and`, `or`, `not`.

### Example: Trigger only when item names start with "item"

* **Workflow name:** `TemporalWorkflowPrintItem_ItemCreate`
* **Filter rule:** `starts with(name, "item")`

#### What happens at runtime:

1. A client runs the `CreateInventoryItem` mutation
2. The system emits an event `InventoryItem.create` with this `eventData`.
3. Workflow-service checks all active workflows listening to create-item events.
4. For `TemporalWorkflowPrintItem_ItemCreate`, it evaluates `starts with(name, "item")`:
   * If `name = "item_123"`, expression is **true** -> the workflow is launched.
   * If `name = "product_456"`, expression is **false** -> the workflow is skipped.

With **Active** and **FilterRule**, users have full control over when and how the workflows are triggered.


# Movements

Movement Concepts

Audience: Logistics Manager

## Movements in the pyck Inventory System

### Understanding Movements in pyck

In the pyck system, we use the term "movements" to track any changes in inventory position or status throughout your supply chain. Unlike traditional WMS that often use the term "transport" (which primarily focuses on physical relocation), our "movements" concept is more comprehensive and flexible.

#### Why We Call Them "Movements" Instead of "Transport"

The term "movements" was deliberately chosen to distinguish our system from traditional WMS terminology. This distinction offers several benefits:

1. **Broader scope**: Movements encompass all inventory status changes, not just physical transportation
2. **System coexistence**: When implementing pyck alongside your existing WMS, this terminology difference helps avoid confusion during transition periods
3. **Process clarity**: Teams can clearly differentiate between processes managed in each system during partial implementations

### Types of Movements in pyck

The pyck system supports three primary types of movements:

#### 1. Item Movements

Item movements track the transfer of specific quantities of products between repositories. This could be moving products between warehouses, from reserve storage to picking locations, or from a warehouse to a retail store.

#### 2. Repository Movements

Repository movements change the parent-child relationship between storage locations. This could be reorganizing your warehouse structure by moving an entire section from one zone to another.

In pyck, we consider any storage unit as a "repository" - this includes not just warehouse zones and racks, but also bins, totes, boxes, and palettes. This approach offers powerful flexibility in managing your inventory:

* **Nested Storage Hierarchy**: You can create parent-child relationships between storage units (e.g., a bin within a rack, or multiple boxes on a palette)
* **Bulk Movements**: When you need to move an entire palette of products, you can create a single repository movement instead of individual item movements for each product on the palette
* **Location Tracking**: Track the exact location of mobile storage units like totes and palettes throughout your warehouse

For example, if you have a palette containing 50 boxes of products and need to move it from receiving to bulk storage, you can:

1. Set up the palette as a repository
2. Place product boxes as child repositories of the palette
3. Create a single repository movement for the palette
4. All child boxes automatically maintain their relationship with the palette

This significantly reduces the administrative overhead of tracking high-volume movements across your operation.

#### 3. Collection Movements

Collection movements group multiple related movements that should be executed in a specific sequence. This ensures complex operations maintain inventory accuracy throughout the process.

### Historical Inventory Tracking

Unlike many traditional inventory systems that only maintain current stock levels, pyck's movement-based approach creates a complete historical record of your inventory. Every time a movement occurs, pyck appends a new stock record rather than simply updating the existing one.

This append-only approach delivers powerful historical insights:

#### Point-in-Time Inventory Queries

With pyck, you can answer inventory questions not just about the present, but about any point in the past:

* **Current stock queries**: "How many iPhones do I have in my warehouse right now?"
* **Location-specific queries**: "How many iPhones do I have in Zone A?"
* **Container-specific queries**: "How many iPhones do I have on Palette X?"
* **Historical queries**: "How many iPhones did I have in Zone A yesterday at 9:15 PM?"
* **Trend analysis**: "How have our iPhone stock levels changed over the past month?"

#### Efficient Database Architecture

Despite storing this rich historical data, pyck's inventory engine is designed for performance:

* **Optimized queries**: Point-in-time inventory lookups are executed as direct database queries
* **No recursive calculations**: The system doesn't need to traverse complex repository hierarchies
* **No child selection overhead**: No need to aggregate multiple records to determine stock levels
* **Index optimization**: Database indexes are specifically designed for both current and historical queries

This architecture allows you to access both real-time and historical inventory information with minimal system overhead, enabling fast decision-making even in high-volume operations.

### Benefits of Movement Tracking in pyck

As a Logistics Manager, tracking movements in pyck provides you with several advantages:

1. **Complete Visibility**: Track every item's location and status in real-time across your entire operation
2. **Predictive Planning**: Anticipate stock levels based on planned movements before they occur
3. **Hierarchical Control**: Manage both individual item quantities and entire storage section relocations
4. **Sequenced Operations**: Ensure complex movements follow the proper order through collection movements
5. **Transition Compatibility**: Run pyck alongside existing WMS systems during phased implementation

### Implementation Strategy When Replacing Existing WMS

When implementing pyck while maintaining your current WMS, the distinct "movements" terminology offers significant benefits:

* **Clear Boundaries**: Staff can easily understand which system handles which processes
* **Phased Training**: Teams can learn the new system while maintaining operations in the familiar environment
* **Reduced Errors**: Less confusion about where to record inventory changes during transition
* **Simplified Validation**: Easier to compare and verify data between systems when terminology is distinct

By carefully planning which movement types to migrate first, you can achieve a gradual, controlled transition from your existing WMS to the more flexible and comprehensive pyck system.


# Authentication

Audience: Programmer

## Overview

pyck uses ZITADEL for authentication and authorization. This document explains how to implement authentication when integrating with the pyck backend API.

## Authentication Flow

1. Authentication is handled via JWT tokens or Personal Access Tokens (PATs)
2. The authentication middleware validates these tokens against ZITADEL
3. User information, including roles and tenant information, is extracted and added to the request context

## Authentication Methods

### JWT Authentication

* Standard OpenID Connect flow using JWT tokens
* Tokens are validated against ZITADEL's JWKS endpoint
* Token validation includes signature verification and claims validation

### Personal Access Token (PAT) Authentication

* Alternative authentication method using long-lived tokens
* PATs are introspected against ZITADEL's token introspection endpoint
* Results are cached to improve performance

## Authorization

### Roles and Permissions

The backend supports the following roles with increasing privilege levels:

* Reader (1000): Read-only access
* Writer (1001): Read and write access
* Admin (1002): Administrative access
* System (1003): System-level access

### Tenant Isolation

* Users are associated with a tenant (organization)
* Tenant ID can be specified via HTTP headers during authentication
* Authentication ensures users can only access resources within their tenant

## Implementation Details

### Authentication Header

* All authenticated requests require: `Authorization: Bearer <token>`
* Where `<token>` is either a valid JWT or PAT

### Error Handling

#### HTTP Error Response Format

All HTTP endpoints (including authentication, health checks, webhooks, and file handlers) return errors in a standardized JSON format:

```json
{
  "error": "Error message description"
}
```

This applies to all non-GraphQL HTTP endpoints. For GraphQL-specific error handling, see the [GraphQL Error Handling](/graphql-api/error-handling) documentation.

#### Authentication Errors

* Authentication errors return HTTP 401 Unauthorized status codes
* All error responses follow the JSON format shown above
* Common errors include expired tokens, invalid signatures, or insufficient permissions

**Example authentication error response:**

```json
{
  "error": "Unauthorized"
}
```

### Unauthenticated Endpoints

Certain endpoints don't require authentication:

* Health check endpoints (`/health`)
* Metrics endpoints (`/metrics`)
* Webhook endpoints (paths containing `/webhook/`)
* Company registration GraphQL mutation
* Tenant registration GraphQL mutation (registerTenant)

## Frontend Configuration Discovery

pyck provides a `/static/settings.json` endpoint that frontends can use to discover OIDC runtime configuration dynamically, eliminating the need to hardcode environment-specific values.

### Endpoint

```
GET /static/settings.json
```

### Response Format

```json
{
  "appUrl": "https://app.example.com",
  "authority": "https://auth.example.com",
  "authorityClientId": "123456789",
  "debug": false,
  "environment": "production",
  "graphqlClientUri": "https://app.example.com/graphql",
  "redirectUri": "https://app.example.com/auth/callback",
  "features": {},
  "version": "1.0.0",
  "otelUrl": "https://otel.example.com",
  "otelIngestKey": "key123"
}
```

### Usage

Frontend applications should fetch this endpoint at startup to configure their OIDC client and other runtime settings. This approach ensures configuration values remain consistent across environments without requiring separate build artifacts.

**Example:**

```javascript
const response = await fetch('/static/settings.json');
const settings = await response.json();

// Configure OIDC client
const authConfig = {
  authority: settings.authority,
  client_id: settings.authorityClientId,
  redirect_uri: settings.redirectUri
};
```

## Development Guide

When developing against the pyck API, you'll need to:

1. Obtain a valid token from ZITADEL
2. Include this token in the Authorization header of all API requests
3. Implement token refresh logic when tokens expire
4. Handle authentication errors appropriately in your client application

## Testing Authentication

For testing purposes, you can:

1. Use the ZITADEL developer console to generate test tokens
2. Verify token validity using the introspection endpoint
3. Test different roles to ensure proper authorization behavior

## Tenant Registration Email Behavior

When using the [`registerTenant`](/graphql-api/mutations/registertenant) mutation, the system allows re-use of the same admin email address across multiple tenant registrations. Each tenant receives a unique tenant-specific primary email (e.g., `user@tenant1.example.com`, `user@tenant2.example.com`), with the original email added as an alias.

**Important:** Cross-tenant authorization is not supported. A user created for one tenant cannot access another tenant's resources, even if they share the same email alias.

**Recommendation:** Use unique email addresses for each tenant registration to avoid confusion and ensure clear account separation.

For detailed information, see the [registerTenant mutation documentation](/graphql-api/mutations/registertenant).


# Headers

Audience: Programmer

## Overview

This document details the HTTP headers used when interacting with the pyck API. These headers control authentication, tenant context, and query behavior.

## Required Headers

### Authorization

```
Authorization: Bearer <token>
```

* The token can be either a JWT or a Personal Access Token (PAT)
* Example: `Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjEu...`
* Missing or invalid tokens result in 403 Forbidden responses

**NOTE**: The `Authorization` header is required for all authenticated endpoints except the following GraphQL mutations/queries:

* `registerTenant`

## Tenant Context Headers

### X-Pyck-Tenant-Id

```
X-Pyck-Tenant-Id: <ID1>,<ID2>,...
```

* Specifies one or more tenants (organizations) for the request
* Used for both query and mutation operations
  * Example: `X-Pyck-Tenant-Id: d4b5319e-1daa-57ed-9676-c6bfc717cf76`
* To provide multiple tenant IDs, you can set the header multiple times and/or add multiple tenant IDs to a single header by separating them with a comma
  * Example: `X-Pyck-Tenant-Id: d4b5319e-1daa-57ed-9676-c6bfc717cf76,7cdbc30a-6f27-5aa1-bd4a-e7d5106075a5`
* You can use the special tenant ID `all` to select all tenants the user has access to.
  * Example: `X-Pyck-Tenant-Id: all`
* For query operations, if not provided, it defaults to `all`.
* For mutations (create/update/delete), you must always provide exactly one tenant ID. You cannot use the special `all` tenant ID for mutations.

### Multi-Tenant Operations

When working with multi-tenant contexts:

* Query operations can use `X-Pyck-Tenant-Id` to retrieve data from one or more tenant contexts
* Mutation operations must use exactly one tenant in `X-Pyck-Tenant-Id`
* The system validates that tenants specified in headers are accessible to the authenticated user

### Setting the Tenant Context for Mutations

All mutation operations require an unambiguous tenant context. While query operations can span multiple tenants, mutations must target exactly one tenant for data integrity.

**For users with access to a single tenant:**

* The tenant context is automatically inferred from the JWT when the `X-Pyck-Tenant-Id` header is omitted
* This provides a convenient default for single-tenant scenarios

**For users with access to multiple tenants:**

* The `X-Pyck-Tenant-Id` header is mandatory
* The API will return an error if the header is missing
* You must explicitly specify which tenant the mutation should affect

**For system users and service tokens:**

* System users operate differently - they have no default tenant context by design, as they can operate across all tenant boundaries
* When performing mutations with a system user token, you must always include the `X-Pyck-Tenant-Id` header to explicitly specify which tenant the mutation should affect
* Omitting this header will result in the error message: `"cannot determine mutation tenant ID"`

**Best practice:** To avoid errors, always include `X-Pyck-Tenant-Id: <tenant-uuid>` in your mutation requests when using system tokens or when you have access to multiple tenants.

## Additional Headers

### X-Pyck-Feature

```
X-Pyck-Feature: <FEATURE1>,<FEATURE2>,...
```

* Used to selectively enable additional features in the API
* Can be provided multiple times with one or more feature IDs separated by comma

The following features can be toggled on:

#### showdeleted

* Controls whether deleted resources should be included in query results
* Example: `X-Pyck-Feature: showdeleted`

## Response Headers

### X-Request-ID

```
X-Request-ID: <uuid>
```

* Automatically included in all HTTP responses from the pyck API
* Contains a unique UUID v7 identifier generated by the server for each request
* Used for request tracing, debugging, and support purposes
* Example: `X-Request-ID: 01010101-0202-7303-8404-050505050505`

**Use cases:**

* **Debugging**: Include this ID when reporting issues to help support teams locate specific requests in logs
* **Request tracing**: Track a request's flow through the system across multiple services
* **Correlation**: The same request ID appears in server logs, making it easier to correlate API requests with backend operations

**Note:** The request ID is always server-generated. Any client-supplied `X-Request-ID` header in the request will be ignored.

## Content-Type Headers

### For API Requests

```
Content-Type: application/json; charset=UTF-8
```

* Required for all POST requests to the API
* All request bodies should be valid JSON

## Authentication Providers

While ZITADEL is the reference implementation for authentication in pyck, the system is designed to support other identity providers. The headers and authentication mechanisms described here are part of pyck's API contract and will remain consistent regardless of the underlying authentication provider.

## Best Practices

* Always include the `Authorization` header for authenticated endpoints
* Always explicitly specify the tenant(s) to use. Use `all` to query all tenants.
* Only enable the `showdeleted` feature when specifically needing to access deleted resources
* Set appropriate `Content-Type` headers for all requests


# Service Roles

Per-service capability roles that gate access to individual pyck services

Audience: Programmer

## Overview

pyck gates access to individual backend services with a set of fixed **per-service capability roles**. This is a thin layer on top of the unchanged reader/writer/admin ladder: the ladder still governs what a user may do once past the gate, while a service role governs whether the user may reach the service at all.

The roles are sourced from ZITADEL project roles (seeded at bootstrap); pyck holds no separate database copy.

## Gated and open services

| Service    | Gated? | Required role       |
| ---------- | ------ | ------------------- |
| inventory  | yes    | `inventory_service` |
| picking    | yes    | `picking_service`   |
| receiving  | yes    | `receiving_service` |
| file       | yes    | `file_service`      |
| main-data  | yes    | `main_data_service` |
| management | no     | —                   |
| workflow   | no     | —                   |

A user who does not hold the relevant service role is denied with an HTTP `403 Forbidden` before the request reaches the gated service. `management` (including the role-assignment API below) and `workflow` are intentionally not gated.

## How the gate resolves which tenants it checks

The gate evaluates the service role against **the tenant(s) the request operates on**, which are derived from the [`X-Pyck-Tenant-Id`](/development/headers#x-pyck-tenant-id) header exactly as every other request is:

* A request **without** the header defaults to `all`, which expands to **every tenant the user holds a ladder role in**.
* A request **with** the header operates on the tenant(s) it names.

The gate then requires the service role in **every** tenant in that set (an AND, not an OR).

This has a consequence worth calling out explicitly:

> A user who holds, for example, `inventory_service` in only **some** of their tenants is **denied on the default (header-less) request**, because that request resolves to *all* of their tenants and the role is missing in at least one of them. To proceed, the caller must scope the request to a qualifying tenant with `X-Pyck-Tenant-Id: <tenant-uuid>`.

This is fail-closed but can be surprising — if a default request returns `403` where you expected access, narrow `X-Pyck-Tenant-Id` to the specific tenant where the user holds the service role.

System users and service tokens bypass the gate.

## Exception: the public file-alias route

One route is intentionally **outside** the gate and is therefore **not** subject to the per-service role restriction:

```
GET /api/v1/files/{tenantId}/{alias}
```

This is the pre-existing public-alias handler. It serves only files that have an explicit public alias, scoped to the `tenantId` in the path, and redirects to a short-lived pre-signed URL. It does not require the `file_service` role — its only access control is knowing a valid `(tenantId, alias)` pair. Do not assume the file service is fully gated: GraphQL traffic to the file service is gated, but this alias route is public by design.

## Managing service roles

Service roles are assigned and inspected through the management GraphQL API (tenant-admin only):

* `serviceRoles` — list the assignable per-service roles.
* `userServiceRoles` — list the roles a user currently holds in a tenant.
* `assignRoles` — add one or more service roles to a user (additive).
* `removeRoles` — remove one or more service roles from a user (idempotent).

Access is **opt-in with no backfill**: existing users are denied on the gated services until a tenant admin assigns them the relevant role.

## Related

* [HTTP Headers](/development/headers) — `X-Pyck-Tenant-Id` and tenant context.
* [Authentication](/development/authentication) — the reader/writer/admin/system ladder.


# Networking Requirements

Network requirements and firewall rules for pyck.cloud SaaS service

Audience: System Administrator

## Overview

This document outlines the network requirements and firewall configurations needed to integrate with pyck's SaaS service at pyck.cloud. pyck uses multiple protocols over standard HTTPS ports and requires support for long-lived connections.

## Protocols and Ports

pyck consolidates all communication through standard web ports:

* **Port 80 (HTTP)**: Used exclusively for redirecting browsers to HTTPS
* **Port 443 (HTTPS)**: All application traffic runs on this port using multiple protocols:
  * HTTPS (standard HTTP/2 and HTTP/1.1)
  * gRPC (over HTTP/2)
  * WebSockets (for real-time bidirectional communication)

### Long-Lived Connections

**Important**: Your network infrastructure must support long-lived connections:

* WebSocket connections may remain open for extended periods
* gRPC streaming connections can be persistent
* Proxy servers and firewalls must be configured to:
  * Not terminate idle connections prematurely
  * Support WebSocket protocol upgrades
  * Handle HTTP/2 traffic properly for gRPC
  * Maintain connection state for streaming protocols

## pyck.cloud SaaS Service

When using pyck's SaaS offering, additional network considerations apply due to the dynamic, auto-scaling infrastructure. Traffic flows in two directions, and each direction is whitelisted differently:

* **Client → server** (your network to pyck): whitelist by **domain** (`*.pyck.cloud`), because backend IPs change constantly.
* **Server → client** (pyck into your network): whitelist by **IP**, using the fixed set published at `ips.pyck.cloud`.

### Outbound Traffic to pyck (Client → Server)

For all traffic originating from your network to pyck:

* **Whitelist all outgoing traffic to `*.pyck.cloud`**: Every pyck endpoint lives under `pyck.cloud` or a subdomain. Because the SaaS platform is auto-scaling and its backend IPs change frequently, you must allow egress by **domain** (`*.pyck.cloud`) rather than by fixed IP.
* **Port 443 (HTTPS)**: Required for all API and application access.
* **Port 80 (HTTP)**: Optional, only used for browser redirects to HTTPS.

Some endpoints are **client → server only** — your systems connect out to them, but they never call back into your network. For example, `debug.pyck.cloud` is used purely for outbound diagnostic sessions. These endpoints:

* Are already covered by whitelisting egress to `*.pyck.cloud`.
* Are **not** published in the `ips.pyck.cloud` A record, because pyck never initiates connections into your network from them.

### Inbound Traffic from pyck (Server → Client)

When pyck needs to reach systems in your network (callbacks, webhooks, and other server-initiated traffic):

* **Source IPs**: All such traffic originates from the fixed set of IPs published at `ips.pyck.cloud`. This set includes pyck's **egress proxy**, through which pyck routes its outbound calls to customer networks.
* **Protocols**: HTTPS, gRPC, WebSockets (all over port 443).
* **Firewall Rules**: Whitelist all IPs from `ips.pyck.cloud` (including the proxy) for **inbound** connections on port 443.

**IP Address Discovery**:

* Domain: `ips.pyck.cloud`
* Published as both A records (individual IPs) and TXT records (comma-separated list)
* Query both record types to get the complete list of IPs

Example DNS queries:

```bash
# Get A records
dig A ips.pyck.cloud

# Get TXT record with comma-separated IPs
dig TXT ips.pyck.cloud
```

Only endpoints that can initiate connections into your network appear in `ips.pyck.cloud`. Client → server-only endpoints such as `debug.pyck.cloud` are intentionally excluded.

### Dynamic Infrastructure and Auto-Scaling

pyck SaaS runs on Kubernetes with auto-scaling enabled:

* **Host Changes**: Backend hosts may change frequently
* **Typical Frequency**: Hosts can change every few minutes during normal operation
* **High Load**: Under high load conditions, changes can occur as frequently as every 5 minutes
* **DNS TTL**: Always respect the TTL values returned by pyck DNS servers
* **Recommendation**: Do not cache DNS responses longer than the specified TTL

## Troubleshooting

### Connection Timeouts

If experiencing connection timeouts:

* Verify load balancer timeout settings (should be 10+ minutes)
* Check that WebSocket upgrades are not being blocked
* Ensure HTTP/2 is enabled for gRPC traffic

### IP Address Changes

If callbacks from pyck.cloud are being blocked:

* Re-query `ips.pyck.cloud` to get the latest IP list
* Verify your DNS cache respects TTL values
* Check firewall logs for blocked connection attempts
* Update whitelist rules with the current IP addresses

### Protocol Issues

If specific features are not working:

* Verify HTTP/2 support is enabled (required for gRPC)
* Check that WebSocket protocol upgrades are allowed
* Ensure TLS 1.2 or higher is supported
* Confirm no middleboxes are blocking or modifying traffic


# Workflows

Audience: Programmer

## Overview

pyck combines Temporal workflow engine with our CRUD+ API to create complete, customized warehouse software solutions. This document explains the workflow architecture, integration points, and development patterns.

## System Architecture

### Key Components

1. **pyck Core Services**: Our CRUD+ microservices providing foundational warehouse functionality
2. **Temporal Service**: Durable execution service integrated within our core
3. **Database**: Persistent storage for both pyck services and Temporal
4. **API Layer**: GraphQL API from pyck services and gRPC API from Temporal
5. **External Workflows**: Custom workflow implementations that operate outside the core system
6. **Frontend Applications**: Mobile and web UIs that interact with the system

### Workflow Architecture

```
                         ┌─────────────────────────────────────────────┐
                         │              pyck Core                      │
                         │                                             │
                         │  ┌─────────────┐    ┌─────────────────┐     │
                         │  │             │    │                 │     │
                         │  │ Database    │◄───┤ Core Services   │     │
                         │  │             │    │                 │     │
                         │  └─────────────┘    └────────┬────────┘     │
                         │                             ▲               │
                         │                             │               │
                         │  ┌─────────────┐            │               │
                         │  │             │            │               │
                         │  │ Temporal    │────────────┘               │
                         │  │             │                            │
                         │  └─────────────┘                            │
                         │                                             │
                         └─────────────┬──────────────┬────────────────┘
                                       │              │
                                       ▼              ▼
                         ┌─────────────────┐    ┌────────────────┐
                         │                 │    │                │
                         │  GraphQL API    │    │  gRPC API      │
                         │                 │    │  (Temporal)    │
                         └────────┬────────┘    └────────┬───────┘
                                  │                      │
                                  ▼                      ▼
           ┌─────────────────────────────────────────────────────────────┐
           │                     External Systems                         │
           │                                                             │
           │  ┌─────────────────┐                  ┌─────────────────┐   │
           │  │                 │                  │                 │   │
           │  │ Workflows       │────────────────►│ Frontend Apps   │   │
           │  │                 │                  │                 │   │
           │  └─────────────────┘                  └─────────────────┘   │
           │                                                             │
           └─────────────────────────────────────────────────────────────┘
```

### Why Temporal?

Temporal provides critical capabilities for warehouse operations:

1. **Crash-proof Execution**: Workflows never lose state, even when systems fail
2. **Fault Tolerance**: Business logic continues despite network failures or API outages
3. **Long-running Processes**: Support for workflows that run for days, weeks, or months
4. **Task Retries**: Automatic retries with configurable policies for intermittent failures
5. **Visibility**: Complete history and real-time status of workflow executions

### Per-Tenant Worker Deployment

pyck automatically provisions dedicated Temporal workers for each tenant during registration:

* **Automatic Setup**: When a tenant is registered via the `registerTenant` mutation, the system automatically creates a Kubernetes-based Temporal worker deployment for that tenant
* **Isolation**: Each tenant runs workflows in its own dedicated worker, ensuring workload isolation
* **Kubernetes Native**: Workers are deployed using the temporal-worker-controller as `TemporalWorkerDeployment` custom resources
* **Namespace Mapping**: Each tenant's worker connects to a Temporal namespace matching the tenant ID
* **Configuration**: Worker deployments include environment-specific settings for Temporal connection, pyck gateway URL, and tenant credentials

This architecture eliminates manual worker setup and ensures that each tenant has dedicated computational resources for their workflow executions from the moment of registration.

## Workflow Development

### Setup and Configuration

1. **Project Structure**: A typical warehouse workflow project includes directories for workflow definitions, activity implementations, data models, API clients, worker service entry point, and tests.
2. **Dependencies**: Workflow projects require dependencies for the Temporal SDK and pyck client libraries.

### Workflow Registration

Workflows must be registered with both Temporal and the pyck API. This two-step registration process happens during application startup:

1. **Temporal Registration**: Workflows and activities are registered with the Temporal worker
2. **pyck API Registration**: Workflows are registered with the pyck GraphQL API to associate them with specific events

The registration process maps workflows to specific event types in the system. For example, a workflow named "TemporalWorkflowPicking\_OrderCreate" would be triggered by the "OrderCreate" event.

### Workflow ID Generation

Workflow IDs in pyck are generated deterministically to ensure consistency and prevent duplicate executions:

* **With pyck\_data\_id**: When `pyck_data_id` is present in the search attributes, it is used as the suffix for the workflow ID (e.g., `WorkflowName_<pyck_data_id>`)
* **Without pyck\_data\_id**: When no `pyck_data_id` is provided, a new UUID is generated as the suffix (e.g., `WorkflowName_<uuid>`)

This deterministic ID generation ensures that:

* Workflows tied to specific data entities can be uniquely identified
* Duplicate workflows for the same data entity are prevented
* Workflow state can be reliably tracked across the system

### Workflow Search Attributes

pyck uses Temporal search attributes to enable filtering, querying, and grouping of workflow executions. These search attributes are automatically configured when pyck initializes:

#### Available Search Attributes

* **pyck\_data\_id**: Links the workflow to a specific data entity (e.g., order ID, shipment ID)
* **pyck\_workflow\_assignee**: Identifies the user or team assigned to the workflow
* **pyck\_workflow\_name**: The name of the workflow being executed
* **pyck\_tenant\_id**: The tenant context for multi-tenant deployments
* **pyck\_data\_type**: The type of data entity the workflow operates on
* **pyck\_service**: The pyck service that owns the workflow
* **pyck\_group\_by**: Custom grouping criteria for categorizing and filtering workflows
* **pyck\_title**: Human-readable per-workflow display label shown in the UI (set via `workflowsdk.SetWorkflowTitle`)
* **pyck\_group\_title**: Human-readable label for the workflow group header (set via `workflowsdk.SetGroupTitle`, pairs with `pyck_group_by`)
* **pyck\_sort\_key**: Numeric value used by the UI to impose a stable display order on workflow executions

#### Using Search Attributes

Search attributes can be used to query and filter workflows through the Temporal API:

```javascript
// Example: Find all picking workflows for a specific order
const workflows = await temporal.workflow.list({
  query: 'pyck_workflow_name="OrderPicking" AND pyck_data_id="order-123"'
});

// Example: Find all workflows assigned to a user
const userWorkflows = await temporal.workflow.list({
  query: 'pyck_workflow_assignee="user-456"'
});

// Example: Group workflows by custom criteria
const groupedWorkflows = await temporal.workflow.list({
  query: 'pyck_group_by="priority-high" AND pyck_service="picking"'
});

// Example: Order workflows by sort key
const orderedWorkflows = await temporal.workflow.list({
  query: 'pyck_sort_key >= 10 AND pyck_sort_key <= 99'
});
```

These search attributes enable powerful filtering and reporting capabilities for monitoring and managing warehouse operations across your pyck deployment.

### Setting Workflow Display Labels

The pyck SDK exposes helpers to set per-workflow display metadata as Temporal search attributes. The UI uses these labels for workflow lists and group headers, and clients can filter/sort directly on them through the GraphQL `workflowExecutions` query.

#### SetWorkflowTitle

Use `workflowsdk.SetWorkflowTitle` to write the `pyck_title` search attribute — the per-workflow display label shown in lists and dashboards.

```go
import "github.com/pyck-ai/pyck/backend/workflowsdk"

func MyWorkflow(ctx temporalworkflow.Context, input MyInput) error {
    // Set the display label so the UI can show a human-readable title
    // and so callers can query workflowExecutions(where: {title: ...}).
    if err := workflowsdk.SetWorkflowTitle(ctx, "SKU-123"); err != nil {
        return err
    }

    // ... rest of the workflow
    return nil
}
```

* Passing an empty string clears the attribute so the frontend falls back to the workflow type name:

  ```go
  workflowsdk.SetWorkflowTitle(ctx, "") // unset
  ```
* The attribute is a Temporal **Keyword** type; both equality and prefix/suffix predicates are available via the GraphQL `title*` filters.
* `workflowsdk.GetWorkflowTitle(ctx)` reads the current value.

#### SetGroupTitle

Use `workflowsdk.SetGroupTitle` to write the `pyck_group_title` search attribute — the human-readable label for the workflow group header. It pairs with `pyck_group_by` (the technical join key); set both together so the UI can group workflows under a shared label.

```go
if err := workflowsdk.SetGroupBy(ctx, "order-42"); err != nil {
    return err
}
if err := workflowsdk.SetGroupTitle(ctx, "ORDER-42"); err != nil {
    return err
}
```

* Passing an empty string clears the attribute so the frontend falls back to `"No Group"`.
* `workflowsdk.GetGroupTitle(ctx)` reads the current value.

#### SetSortKey

The `pyck_sort_key` search attribute can be set from within a workflow using the workflowsdk to control the display order of workflow executions in the UI:

```go
import (
  "github.com/pyck-ai/pyck/backend/workflowsdk"
)

// Set a sort key to control display order
func MyWorkflow(ctx workflow.Context) error {
  sortKey := int64(42)
  if err := workflowsdk.SetSortKey(ctx, &sortKey); err != nil {
    return err
  }

  // ... rest of workflow logic

  // Clear the sort key (falls back to default start-time ordering)
  if err := workflowsdk.SetSortKey(ctx, nil); err != nil {
    return err
  }

  return nil
}

// Read the current sort key
func CheckSortKey(ctx workflow.Context) {
  sortKey := workflowsdk.GetSortKey(ctx)
  if sortKey != nil {
    // Sort key is set to *sortKey
  } else {
    // Sort key is not set, will use default ordering
  }
}
```

The sort key is particularly useful when you need workflows to appear in a specific order in the UI, rather than relying solely on start time. Pass `nil` to `SetSortKey` to unset the attribute and fall back to default start-time ordering.

#### Migration from SetWorkflowMemo

`workflowsdk.SetWorkflowMemo` and the associated `WorkflowMemo` struct (with `Title`, `Subtitle`, and `Data` fields) have been **removed**. Memo fields are opaque to Temporal Visibility and cannot be indexed; search attributes are fully queryable.

**Before:**

```go
workflowsdk.SetWorkflowMemo(ctx, workflowsdk.WorkflowMemo{
    Title:    "SKU-123",
    Subtitle: "order-uuid",
    Data:     map[string]any{"priority": "high"},
})
```

**After:**

```go
// The per-workflow title and the group label are now first-class search
// attributes. Custom auxiliary data should move into the workflow input,
// the workflow state, or pyck_group_by depending on its purpose.
workflowsdk.SetWorkflowTitle(ctx, "SKU-123")
workflowsdk.SetGroupBy(ctx, "order-uuid")
workflowsdk.SetGroupTitle(ctx, "ORDER UUID")
```

The signal router also accepts `pyck_title` and `pyck_group_title` keys when propagating attributes from incoming signal payloads, alongside the existing `pyck_workflow_assignee` and `pyck_group_by` keys.

### Workflow Definition

Workflows in Temporal are defined as functions that orchestrate a series of activities. A typical picking workflow would include steps like:

* Fetching order details
* Allocating inventory
* Generating picking tasks
* Updating mobile app UI for picker
* Waiting for picking completion
* Processing results and updating inventory

### Frontend Control Points

Workflows control frontend behavior through a combination of:

1. **Activity Properties**: Each workflow activity can define UI properties that should be displayed
2. **Signal Channels**: Workflows wait for user input through signal channels
3. **NextActivityName**: Defining the next activity tells the frontend what screen to show

### Event Triggering and Signal Routing

Workflows are triggered by events from the system through an advanced signal routing mechanism that differentiates between START and INTERMEDIATE signals:

1. **START Signals**: Create new workflow instances when triggered
2. **INTERMEDIATE Signals**: Forward signals to already running workflow instances

When an event occurs in the pyck system:

* The system uses JetStream-based routing to determine which workflows should be triggered
* START signals will create new workflow instances (or fail if a workflow with the same ID is already running)
* INTERMEDIATE signals will be forwarded to matching running workflows

For example, when an order is created in the system, the "OrderCreate" event is fired, which then triggers the "TemporalWorkflowPicking\_OrderCreate" workflow.

**Important Breaking Change**: As of the latest version, running workflows cannot be reassigned on re-trigger. Attempting to start a workflow that is already running will result in an error. This ensures workflow state consistency and prevents accidental duplicate executions.

## User Input Communication Flow

The communication between Temporal workflows and the frontend when waiting for user input follows a specific stateful pattern:

### 1. Workflow State Management

Workflows maintain their state through a query mechanism that allows external systems to inspect their current state without affecting execution:

1. **Query Handler**: Each workflow exposes its current UI state through a query handler for "nextActivityProperties"
2. **Activity Definition**: The workflow defines what activity the user should perform next
3. **Signal Channels**: The workflow creates channels to receive signals from the frontend
4. **Waiting for Input**: The workflow pauses execution while waiting for user input

### 2. Frontend Interaction Cycle

The frontend interacts with workflows through a well-defined cycle:

1. **Discover Workflows**: Frontend finds workflows assigned to the current user via the `checkAssignedWorkflows` GraphQL mutation
2. **Get Current Activity**: The system retrieves the current activity information from the workflow
3. **Render UI Components**: Frontend displays the appropriate UI based on the activity properties
4. **Collect User Input**: User interacts with the UI and provides the requested information
5. **Submit Input and Get Next Step**: When the user submits input, the frontend calls a single GraphQL mutation (`userDataInput`) that:
   * Sends the user input to the workflow
   * Waits for the workflow to process the input
   * Returns the next activity in the same response

This means the frontend doesn't need to separately poll for the next activity after submitting user input - it gets both acknowledgment of the submitted data and instructions for the next step in a single GraphQL mutation.

### 3. GraphQL Mutation Synchronization

When the `userDataInput` GraphQL mutation is called:

1. **Signal Sending**: The GraphQL resolver sends the user input to the workflow via a Temporal signal
2. **Synchronous Waiting**: The resolver then waits for the workflow to process the input
3. **State Transition Detection**: The resolver monitors the workflow state, waiting for it to change from the current activity to the next activity
4. **Response with Next Step**: Once the workflow updates its state, the GraphQL mutation returns with information about the next activity the frontend should display

### 4. Workflow Processing

Inside the workflow, when it receives user input:

1. **Signal Reception**: The workflow's signal channel receives the user input
2. **State Update**: The workflow updates its activity state to indicate the current activity is passed
3. **Input Processing**: The workflow processes the input, often calling an activity
4. **Next Activity Definition**: The workflow defines the next activity for the user
5. **State Exposure**: The updated state becomes available to the GraphQL resolver

This continuous cycle allows the workflow to drive the frontend state while maintaining the reliability guarantees provided by Temporal's durable execution model.

## BPMN to Code Translation

We use BPMN for visual workflow design and translate it to Temporal code:

1. **BPMN Process**: Designed with logistics team for business requirements
2. **Activities**: BPMN tasks become Temporal activities
3. **Gateways**: BPMN gateways become workflow conditions
4. **Events**: BPMN events map to Temporal signals/triggers

The workflow directory structure typically follows this pattern:

```
processes/
  {priority}_{domain}/
    {id}_{event}/
      activities/      # Activity implementation
      domain/          # Data models
      workflows/       # Workflow definition
      {event}.bpmn     # Visual workflow design
```

## Reference Implementation

For a practical example, see our reference implementation: <https://github.com/pyck-ai/pyck-customer-template>

## Best Practices

1. **Idempotency**: Ensure all activities are idempotent for reliable retries
2. **Deterministic Workflows**: Keep workflows deterministic by moving non-deterministic code to activities
3. **Error Handling**: Use appropriate retry policies for different failure types
4. **Testing**: Write comprehensive tests for workflows and activities
5. **Monitoring**: Set up proper monitoring and alerting using Temporal metrics
6. **Versioning**: Use versioning for workflow changes to handle in-flight workflows


# Locations

Locations, Devices, and User Management

Audience: Programmer

## Overview

pyck provides a comprehensive location and device management system within the Management Service. This system enables physical warehouse layout mapping, device tracking, user check-in/check-out functionality, and inventory repository association with specific locations.

## Core Entities

### Location

Represents a physical area within the warehouse (e.g., workstation, zone, dock).

| Field        | Type   | Description                        |
| ------------ | ------ | ---------------------------------- |
| `id`         | UUID   | Unique identifier                  |
| `name`       | String | Location name (unique per tenant)  |
| `tenantID`   | UUID   | Owning tenant                      |
| `dataTypeID` | UUID   | Optional custom data type          |
| `data`       | Map    | Custom fields defined by data type |

### Device

Represents a physical device (scanner, tablet, workstation terminal).

| Field        | Type   | Description                        |
| ------------ | ------ | ---------------------------------- |
| `id`         | UUID   | Unique identifier                  |
| `name`       | String | Device name (unique per tenant)    |
| `tenantID`   | UUID   | Owning tenant                      |
| `dataTypeID` | UUID   | Optional custom data type          |
| `data`       | Map    | Custom fields defined by data type |

### DeviceLocation

Associates a device with a location. A device can only be assigned to one location at a time.

| Field        | Type | Description         |
| ------------ | ---- | ------------------- |
| `id`         | UUID | Unique identifier   |
| `deviceID`   | UUID | Associated device   |
| `locationID` | UUID | Associated location |

### DeviceUser

Tracks which user is currently checked-in to a device. Only one user can be checked-in to a device at a time.

| Field      | Type | Description       |
| ---------- | ---- | ----------------- |
| `id`       | UUID | Unique identifier |
| `deviceID` | UUID | Associated device |
| `userID`   | UUID | Checked-in user   |

## Entity Relationships

```
Location ──────────────────────────────────────────┐
    │                                              │
    ▼                                              │
DeviceLocation ◄─── Device ◄─── DeviceUser ───► User
                        │
                        │
                        ▼
              InventoryRepository
                 (location_id)
```

Key relationships:

* **Location → DeviceLocation**: One-to-many (a location can have multiple devices)
* **Device → DeviceLocation**: One-to-one (a device is at one location)
* **Device → DeviceUser**: One-to-one (only one user per device)
* **User → DeviceUser**: One-to-many (a user can have check-in history)
* **Location → Repository**: One-to-many (repositories can reference a location)

## GraphQL Operations

### Creating a Location

```graphql
mutation CreateLocation($input: CreateLocationInput!) {
  createLocation(input: $input) {
    location {
      id
      name
      data
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "name": "Workstation-A1"
  }
}
```

### Creating a Device

```graphql
mutation CreateDevice($input: CreateDeviceInput!) {
  createDevice(input: $input) {
    device {
      id
      name
      data
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "name": "Scanner-001"
  }
}
```

### Assigning a Device to a Location

```graphql
mutation SetDeviceLocation($input: CreateDeviceLocationInput!) {
  setDeviceLocation(input: $input) {
    DeviceLocation {
      id
      deviceID
      locationID
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "deviceID": "device-uuid-here",
    "locationID": "location-uuid-here"
  }
}
```

To remove a device from its location:

```graphql
mutation UnsetDeviceLocation($id: ID!) {
  unsetDeviceLocation(id: $id) {
    deletedID
  }
}
```

### User Check-In

When a user starts working at a device:

```graphql
mutation CheckInUserDevice($input: CheckInUserDeviceInput!) {
  checkInUserDevice(input: $input) {
    deviceUser {
      id
      deviceID
      userID
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "deviceID": "device-uuid-here"
  }
}
```

The `userID` is automatically derived from the authenticated user's token.

### User Check-Out

When a user finishes working at a device:

```graphql
mutation CheckOutUserDevice($input: CheckOutUserDeviceInput!) {
  checkOutUserDevice(input: $input) {
    deviceUser {
      id
      deviceID
      userID
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "deviceID": "device-uuid-here"
  }
}
```

### Assigning a Location to a Repository

When creating or updating an inventory repository, you can associate it with a management location:

```graphql
mutation CreateInventoryRepository($input: CreateInventoryRepositoryInput!) {
  createInventoryRepository(input: $input) {
    inventoryRepository {
      id
      name
      locationID
    }
  }
}
```

**Variables:**

```json
{
  "input": {
    "name": "Shelf-A1-001",
    "type": "static",
    "locationID": "location-uuid-here"
  }
}
```


# Architecture

System Architecture

Audience: Programmer

## System Architecture

pyck is a modular microservices platform built in Go that provides a comprehensive logistics solution for warehousing operations. The architecture follows modern microservices principles with clear separation of concerns.

### Core Components

1. **Gateway Service**
   * Aggregates GraphQL schemas from all services
   * Provides a unified API endpoint
   * Handles authentication and request routing
2. **Domain Services**
   * **Main Data Service**: Core data operations and primary data entities
   * **Inventory Service**: Stock levels, item movements, and inventory management
   * **Management Service**: System configurations and company-related information
   * **Picking Service**: Order picking workflow and processing
   * **Receiving Service**: Inbound shipment processing
   * **File Service**: File storage and document management
   * **Workflow Service**: Background task execution and process automation

### Technical Infrastructure

pyck leverages several key technologies:

* **GraphQL**: Main API interface with federation across services
* **PostgreSQL**: Primary data storage
* **NATS.io**: Event streaming and service messaging
* **Temporal.io**: Workflow orchestration and reliable task execution
* **Docker**: Containerization for consistent deployment
* **Zitadel**: Authentication and authorization
* **MinIO/S3**: Object storage for files and attachments

### Service Communication

Services communicate through:

1. **GraphQL Federation**: For data queries and mutations
2. **Event Streaming**: Using NATS for asynchronous events
3. **Workflow Orchestration**: Temporal for complex process flows

### Development Approach

The codebase follows these principles:

* **Go Backend**: All backend services are written in Go
* **Infrastructure as Code**: Docker Compose and Taskfile for automated setup
* **API-First Design**: GraphQL schema definitions drive implementation
* **Code Generation**: Models and GraphQL adapters are generated using entgo
* **CRUD+ System**: Backend provides common basic functions for all warehouses
* **Process Workflows**: Complex business logic implemented via temporal processes

### Deployment Model

pyck can be deployed as:

* **Local Development Environment**: Using Docker Compose
* **Kubernetes Cluster**: Using Helm charts for production deployment

#### Required Environment Variables

All pyck services require the following environment variable:

* **`PYCK_ENV`** (required): Environment identifier used for resource naming and namespace construction
  * Must be set explicitly in all deployment configurations
  * No default value — application will crash at startup if missing
  * Examples: `production`, `staging`, `dev`, `local`
  * Used to construct namespace names (e.g., `pyck-{PYCK_ENV}-workers`)

**Breaking Change Notice**: As of commit `15ffdc33` (April 2026), the previous default value of "local" has been removed. All deployments must now explicitly set `PYCK_ENV` in their environment configuration or ConfigMap.

### Tenant Worker Architecture

pyck implements a per-tenant worker deployment model for Temporal workflows:

* **Automatic Provisioning**: During tenant registration, the system automatically deploys a dedicated Temporal worker for each tenant
* **Kubernetes Integration**: Workers are deployed as Kubernetes custom resources using the temporal-worker-controller
* **Isolation**: Each tenant gets its own worker deployment, ensuring workload isolation and independent scaling
* **Resource Management**: Worker deployments are created in a shared workers namespace with configurable resource limits (CPU: 100m-500m, Memory: 256Mi-512Mi)

#### Worker Deployment Components

When a new tenant is registered, the following Kubernetes resources are created:

1. **Workers Namespace**: A shared namespace for all tenant workers (e.g., `{environment}-workers`)
2. **TemporalConnection CRD**: Defines the connection to the Temporal service (shared per environment)
3. **TemporalWorkerDeployment CRD**: Creates a dedicated worker deployment for the tenant

#### Worker Deployment Configuration

Worker deployments can be configured via environment variables:

* **`PYCK_FLAVOUR_GO_WORKER_REPLICAS`**: Number of worker pod replicas per tenant (default: `2`)
  * Controls horizontal scaling of tenant worker deployments
  * Higher values provide better availability and throughput
  * Should be tuned based on expected workflow load per tenant

#### Worker Health Monitoring

Each Temporal worker automatically exposes a `/health` HTTP endpoint (default port 8080) that verifies the worker is actively polling Temporal. The health check:

* Queries Temporal to confirm this worker's identity appears in the task queue poller list
* Returns **200 OK** when the worker is healthy and polling
* Returns **503 Service Unavailable** when the worker has stopped polling or cannot reach Temporal

Configuration (all optional):

* **`HEALTH_DISABLED`**: Set to `1` to disable health checks
* **`HEALTH_PORT`**: HTTP port (default: `8080`)
* **`HEALTH_INTERVAL`**: Probe frequency (default: `10s`)
* **`HEALTH_TIMEOUT`**: RPC timeout per probe (default: `3s`)
* **`HEALTH_MAX_STALE`**: Maximum age of last success before marking unhealthy (default: `90s`)

This health endpoint integrates with Kubernetes liveness probes and fly.io health checks to automatically restart workers that have silently stopped processing workflows.

This architecture ensures that each tenant's workflow executions run in isolated workers while maintaining efficient resource utilization across the system.


# Migrations

Migration guides for breaking changes in the pyck API

Audience: Programmer

This section contains migration guides for breaking changes in the pyck GraphQL API. Each guide explains what changed, why it changed, and provides step-by-step instructions for updating your code.

## Available Migration Guides

| Guide                                                                         | Description                                                                     |
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| [Relay Connections](/development/migrations/relay-connections)                | All entity relationship fields now return Relay-style Connection objects        |
| [InventoryItem Data Field](/development/migrations/inventory-item-data-field) | The inventoryJSONData field has been removed in favor of the unified data field |

## General Migration Tips

1. **Test in Development First**: Always apply migrations to your development environment before production.
2. **Update Incrementally**: When multiple breaking changes are introduced, migrate one change at a time.
3. **Check Your Queries**: Use GraphQL introspection to verify the new schema structure before updating your queries.
4. **Update Client Libraries**: Ensure your GraphQL client libraries are compatible with the new schema.
5. **Monitor for Errors**: After deploying migrated code, monitor your application for any GraphQL errors.

## Getting Help

If you encounter issues during migration:

* Check the specific migration guide for troubleshooting tips
* Review the [GraphQL Error Handling](https://github.com/pyck-ai/docs/blob/main/development/graphql/error-handling.md) documentation
* Consult the [GraphQL Getting Started](https://github.com/pyck-ai/docs/blob/main/development/graphql/getting-started.md) guide for basics


# Relay Connections

Migration guide for the breaking change from simple list fields to Relay-style Connection objects

Audience: Programmer

## Overview

This guide covers a breaking change in the pyck GraphQL API where all entity relationship fields now return Relay-style Connection objects instead of simple lists. This change enables consistent cursor-based pagination, filtering, and ordering across all relationships.

## What Changed

**Before**: Relationship fields returned simple arrays.

```graphql
type Group {
  users: [User!]
  roles: [Role!]
}
```

**After**: Relationship fields return Connection objects with edges and nodes.

```graphql
type Group {
  users(
    after: Cursor
    first: Int
    before: Cursor
    last: Int
    orderBy: UserOrder
    where: UserWhereInput
  ): UserConnection!
  roles(
    after: Cursor
    first: Int
    before: Cursor
    last: Int
    orderBy: RoleOrder
    where: RoleWhereInput
  ): RoleConnection!
}
```

## Affected Relationship Fields

The following relationship fields have been changed to return Connection objects:

### Inventory Service

| Type                 | Field                                | Connection Type                    |
| -------------------- | ------------------------------------ | ---------------------------------- |
| `InventoryItemSet`   | `items`                              | `InventoryItemConnection`          |
| `ReplenishmentOrder` | `replenishmentOrderItems`            | `ReplenishmentOrderItemConnection` |
| `Repository`         | `itemMovementToRepositories`         | `ItemMovementConnection`           |
| `Repository`         | `itemMovementFromRepositories`       | `ItemMovementConnection`           |
| `Repository`         | `repositoryMovementToRepositories`   | `RepositoryMovementConnection`     |
| `Repository`         | `repositoryMovementFromRepositories` | `RepositoryMovementConnection`     |
| `Repository`         | `repositoryMovementRepositories`     | `RepositoryMovementConnection`     |
| `Repository`         | `repositoryTransactions`             | `TransactionConnection`            |
| `Repository`         | `repositoryStocks`                   | `StockConnection`                  |
| `Repository`         | `children`                           | `RepositoryConnection`             |

### Management Service

| Type       | Field                     | Connection Type            |
| ---------- | ------------------------- | -------------------------- |
| `Device`   | `deviceLocationsDevice`   | `DeviceLocationConnection` |
| `Device`   | `deviceUsersDevice`       | `DeviceUserConnection`     |
| `Group`    | `users`                   | `UserConnection`           |
| `Group`    | `roles`                   | `RoleConnection`           |
| `Location` | `deviceLocationsLocation` | `DeviceLocationConnection` |
| `Role`     | `users`                   | `UserConnection`           |
| `Role`     | `groups`                  | `GroupConnection`          |
| `Role`     | `policies`                | `AccessPolicyConnection`   |
| `Tenant`   | `tenantUsers`             | `UserConnection`           |
| `User`     | `roles`                   | `RoleConnection`           |
| `User`     | `groups`                  | `GroupConnection`          |
| `User`     | `deviceUsersUsers`        | `DeviceUserConnection`     |

### Receiving Service

| Type               | Field          | Connection Type                  |
| ------------------ | -------------- | -------------------------------- |
| `ReceivingInbound` | `inboundItems` | `ReceivingInboundItemConnection` |

### Workflow Service

| Type       | Field             | Connection Type            |
| ---------- | ----------------- | -------------------------- |
| `Workflow` | `workflowSignals` | `WorkflowSignalConnection` |

## Connection Object Structure

All Connection types follow the Relay specification with this structure:

```graphql
type ExampleConnection {
  """A list of edges."""
  edges: [ExampleEdge]

  """Information to aid in pagination."""
  pageInfo: PageInfo!

  """Identifies the total count of items in the connection."""
  totalCount: Int!
}

type ExampleEdge {
  """The item at the end of the edge."""
  node: Example

  """A cursor for use in pagination."""
  cursor: Cursor!
}

type PageInfo {
  """When paginating forwards, are there more items?"""
  hasNextPage: Boolean!

  """When paginating backwards, are there more items?"""
  hasPreviousPage: Boolean!

  """When paginating backwards, the cursor to continue."""
  startCursor: Cursor

  """When paginating forwards, the cursor to continue."""
  endCursor: Cursor
}
```

## Migration Steps

### Step 1: Update Query Structure

Change your queries to use the `edges { node { ... } }` pattern.

**Before:**

```graphql
query GetGroupUsers {
  group(id: "group-uuid") {
    id
    name
    users {
      id
      username
      email
    }
  }
}
```

**After:**

```graphql
query GetGroupUsers {
  group(id: "group-uuid") {
    id
    name
    users {
      edges {
        node {
          id
          username
          email
        }
      }
      totalCount
    }
  }
}
```

### Step 2: Update Response Handling

Update your client code to handle the new response structure.

**Before (JavaScript):**

```javascript
const users = response.data.group.users;
users.forEach(user => {
  console.log(user.username);
});
```

**After (JavaScript):**

```javascript
const usersConnection = response.data.group.users;
const users = usersConnection.edges.map(edge => edge.node);
users.forEach(user => {
  console.log(user.username);
});

// Or access totalCount
console.log(`Total users: ${usersConnection.totalCount}`);
```

### Step 3: Implement Pagination (Optional)

Take advantage of the new pagination capabilities.

```graphql
query GetGroupUsersWithPagination($groupId: ID!, $first: Int, $after: Cursor) {
  group(id: $groupId) {
    id
    name
    users(first: $first, after: $after) {
      edges {
        node {
          id
          username
          email
        }
        cursor
      }
      pageInfo {
        hasNextPage
        endCursor
      }
      totalCount
    }
  }
}
```

**Pagination helper (JavaScript):**

```javascript
async function fetchAllUsers(groupId) {
  const allUsers = [];
  let hasNextPage = true;
  let cursor = null;

  while (hasNextPage) {
    const response = await client.query({
      query: GET_GROUP_USERS,
      variables: { groupId, first: 50, after: cursor }
    });

    const connection = response.data.group.users;
    allUsers.push(...connection.edges.map(e => e.node));

    hasNextPage = connection.pageInfo.hasNextPage;
    cursor = connection.pageInfo.endCursor;
  }

  return allUsers;
}
```

### Step 4: Add Filtering and Ordering (Optional)

Use the new filtering and ordering capabilities on relationship fields.

```graphql
query GetGroupActiveUsers($groupId: ID!) {
  group(id: $groupId) {
    users(
      first: 10
      orderBy: { direction: ASC, field: USERNAME }
      where: { isAdmin: false }
    ) {
      edges {
        node {
          id
          username
          email
        }
      }
      totalCount
    }
  }
}
```

## Complete Migration Examples

### Example 1: InventoryItemSet with Items

**Before:**

```graphql
query {
  inventoryItemSets(first: 10) {
    edges {
      node {
        id
        sku
        items {
          id
          sku
          data
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  inventoryItemSets(first: 10) {
    edges {
      node {
        id
        sku
        items(first: 100) {
          edges {
            node {
              id
              sku
              data
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 2: ReceivingInbound with InboundItems

**Before:**

```graphql
query {
  receivingInbounds(first: 10) {
    edges {
      node {
        id
        orderID
        inboundItems {
          sku
          quantity
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  receivingInbounds(first: 10) {
    edges {
      node {
        id
        orderID
        inboundItems {
          edges {
            node {
              sku
              quantity
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 3: Workflow with Signals

**Before:**

```graphql
query {
  workflows(first: 10) {
    edges {
      node {
        id
        name
        workflowSignals {
          id
          natsTopic
          temporalSignalType
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  workflows(first: 10) {
    edges {
      node {
        id
        name
        workflowSignals {
          edges {
            node {
              id
              natsTopic
              temporalSignalType
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 4: Role with Users, Groups, and Policies

**Before:**

```graphql
query {
  roles(first: 10) {
    edges {
      node {
        id
        name
        users {
          id
          username
        }
        groups {
          id
          name
        }
        policies {
          id
          resource
          action
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  roles(first: 10) {
    edges {
      node {
        id
        name
        users {
          edges {
            node {
              id
              username
            }
          }
          totalCount
        }
        groups {
          edges {
            node {
              id
              name
            }
          }
          totalCount
        }
        policies {
          edges {
            node {
              id
              resource
              action
            }
          }
          totalCount
        }
      }
    }
  }
}
```

## Benefits of This Change

1. **Consistent Pagination**: All relationship fields now support cursor-based pagination with `first`, `last`, `before`, and `after` arguments.
2. **Filtering on Relationships**: Apply WhereInput filters directly on relationship fields to reduce data transfer.
3. **Ordering on Relationships**: Order related items using OrderBy inputs on the relationship itself.
4. **Total Count**: Always know how many related items exist with the `totalCount` field.
5. **Relay Compliance**: Full compliance with the [Relay Cursor Connections Specification](https://relay.dev/graphql/connections.htm).

## Troubleshooting

### Error: Cannot query field "edges" on type "\[User!]"

This error indicates you are using the old query structure. Update your query to use the Connection pattern:

```graphql
# Wrong
users { id }

# Correct
users { edges { node { id } } }
```

### Error: Cannot query field "totalCount"

Ensure you are querying `totalCount` at the Connection level, not inside edges or node:

```graphql
# Wrong
users { edges { totalCount } }

# Correct
users {
  edges { node { id } }
  totalCount
}
```

### Performance Considerations

When fetching nested relationships, always use the `first` argument to limit results:

```graphql
# Recommended: Limit nested connections
inventoryItemSets(first: 10) {
  edges {
    node {
      items(first: 50) {  # Limit nested items
        edges { node { id } }
      }
    }
  }
}
```

## Related Documentation

* [PageInfo Type](https://github.com/pyck-ai/docs/blob/main/development/graphql/types/PageInfo.md)
* [Relay Cursor Connections Specification](https://relay.dev/graphql/connections.htm)
* [GraphQL Getting Started](https://github.com/pyck-ai/docs/blob/main/development/graphql/getting-started.md)


# InventoryItem Data Field

Migration guide for the breaking change from inventoryJSONData to the unified data field

Audience: Programmer

## Overview

This guide covers a breaking change in the pyck GraphQL API where the `inventoryJSONData` field has been removed from the `InventoryItem` type. This field has been replaced with the unified `data` field that is now available across all entity types through the shared DataMixin.

## What Changed

**Before**: InventoryItem had a separate `inventoryJSONData` field for storing custom JSON data.

```graphql
type InventoryItem {
  id: ID!
  sku: String!
  inventoryJSONData: Map  # Removed
  # ... other fields
}
```

**After**: InventoryItem uses the unified `data` field from the WithCustomData interface.

```graphql
type InventoryItem implements WithCustomData {
  id: ID!
  sku: String!
  data: Map
  # ... other fields
}
```

## Breaking Changes

1. **Field Removed**: The `inventoryJSONData` field no longer exists on `InventoryItem`
2. **Database Migration**: The `inventory_json_data` column has been removed from the items table
3. **Data Preserved**: All data previously stored in `inventoryJSONData` has been migrated to the `data` field

## Migration Steps

### Step 1: Update GraphQL Queries

Replace all occurrences of `inventoryJSONData` with `data` in your queries.

**Before:**

```graphql
query GetInventoryItems {
  inventoryItems(first: 10) {
    edges {
      node {
        id
        sku
        inventoryJSONData
      }
    }
  }
}
```

**After:**

```graphql
query GetInventoryItems {
  inventoryItems(first: 10) {
    edges {
      node {
        id
        sku
        data
      }
    }
  }
}
```

### Step 2: Update Mutations

Update create and update mutations to use `data` instead of `inventoryJSONData`.

**Before:**

```graphql
mutation CreateItem($input: CreateInventoryItemInput!) {
  createInventoryItem(input: $input) {
    id
    sku
    inventoryJSONData
  }
}

# Variables
{
  "input": {
    "sku": "ITEM-001",
    "inventoryJSONData": {
      "weight": 1.5,
      "color": "blue"
    }
  }
}
```

**After:**

```graphql
mutation CreateItem($input: CreateInventoryItemInput!) {
  createInventoryItem(input: $input) {
    id
    sku
    data
  }
}

# Variables
{
  "input": {
    "sku": "ITEM-001",
    "data": {
      "weight": 1.5,
      "color": "blue"
    }
  }
}
```

### Step 3: Update Filter Queries

Update where clauses that filter on JSON data fields.

**Before:**

```graphql
query GetItemsByWeight {
  inventoryItems(
    where: {
      inventoryJSONDataHasKey: "weight"
    }
  ) {
    edges {
      node {
        id
        sku
        inventoryJSONData
      }
    }
  }
}
```

**After:**

```graphql
query GetItemsByWeight {
  inventoryItems(
    where: {
      dataHasKey: "weight"
    }
  ) {
    edges {
      node {
        id
        sku
        data
      }
    }
  }
}
```

### Step 4: Update Client Code

Update your client code to use the new field name.

**Before (JavaScript):**

```javascript
const items = response.data.inventoryItems.edges.map(edge => ({
  id: edge.node.id,
  sku: edge.node.sku,
  customData: edge.node.inventoryJSONData
}));
```

**After (JavaScript):**

```javascript
const items = response.data.inventoryItems.edges.map(edge => ({
  id: edge.node.id,
  sku: edge.node.sku,
  customData: edge.node.data
}));
```

## Complete Migration Examples

### Example 1: Query with Custom Data

**Before:**

```graphql
query GetItemsWithMetadata {
  inventoryItems(
    first: 20,
    where: {
      inventoryJSONDataHasKey: "metadata"
    }
  ) {
    edges {
      node {
        id
        sku
        inventoryJSONData
        createdAt
      }
    }
    totalCount
  }
}
```

**After:**

```graphql
query GetItemsWithMetadata {
  inventoryItems(
    first: 20,
    where: {
      dataHasKey: "metadata"
    }
  ) {
    edges {
      node {
        id
        sku
        data
        createdAt
      }
    }
    totalCount
  }
}
```

### Example 2: Create Item with Custom Data

**Before:**

```graphql
mutation CreateProductItem {
  createInventoryItem(input: {
    sku: "PROD-12345",
    inventoryJSONData: {
      category: "electronics",
      manufacturer: "Acme Corp",
      warranty: "2 years"
    }
  }) {
    id
    sku
    inventoryJSONData
  }
}
```

**After:**

```graphql
mutation CreateProductItem {
  createInventoryItem(input: {
    sku: "PROD-12345",
    data: {
      category: "electronics",
      manufacturer: "Acme Corp",
      warranty: "2 years"
    }
  }) {
    id
    sku
    data
  }
}
```

### Example 3: Update Item Custom Data

**Before:**

```graphql
mutation UpdateItemData($id: ID!, $newData: Map!) {
  updateInventoryItem(id: $id, input: {
    inventoryJSONData: $newData
  }) {
    id
    sku
    inventoryJSONData
  }
}
```

**After:**

```graphql
mutation UpdateItemData($id: ID!, $newData: Map!) {
  updateInventoryItem(id: $id, input: {
    data: $newData
  }) {
    id
    sku
    data
  }
}
```

## Benefits of This Change

1. **Consistency**: All entity types now use the same `data` field through the `WithCustomData` interface
2. **Simplified Schema**: Reduces duplication by using shared mixins across entity types
3. **Unified Filtering**: Consistent filter names (`dataHasKey`, `dataContains`, etc.) across all entity types
4. **Better Type System**: Leverages GraphQL interfaces for shared behavior

## Filter Input Changes

The following filter fields have been renamed for consistency:

| Old Field Name              | New Field Name |
| --------------------------- | -------------- |
| `inventoryJSONData`         | `data`         |
| `inventoryJSONDataHasKey`   | `dataHasKey`   |
| `inventoryJSONDataIn`       | `dataIn`       |
| `inventoryJSONDataContains` | `dataContains` |

## Troubleshooting

### Error: Cannot query field "inventoryJSONData" on type "InventoryItem"

This error indicates you are still using the old field name. Update your query to use `data`:

```graphql
# Wrong
inventoryItems {
  edges {
    node {
      inventoryJSONData
    }
  }
}

# Correct
inventoryItems {
  edges {
    node {
      data
    }
  }
}
```

### Error: Field "inventoryJSONDataHasKey" is not defined

Update your where clause to use the new filter field names:

```graphql
# Wrong
where: {
  inventoryJSONDataHasKey: "category"
}

# Correct
where: {
  dataHasKey: "category"
}
```

## Related Documentation

* [WithCustomData Interface](https://github.com/pyck-ai/docs/blob/main/development/graphql/interfaces/WithCustomData.md)
* [InventoryItem Type](https://github.com/pyck-ai/docs/blob/main/development/graphql/types/InventoryItem.md)
* [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/development/graphql/advanced/json-field-queries.md)
* [Map Scalar](https://github.com/pyck-ai/docs/blob/main/development/graphql/scalars/Map.md)


# Overview

How the Shopify app connects your store to pyck

Audience: Logistics Manager

The pyck Shopify app links a Shopify store to your warehouse. It copies your shop data into pyck so the warehouse knows what to pick, and it lets pyck report back what it shipped and what is on the shelf.

## The two directions

Everything the app does falls into one of two directions.

| Direction       | What travels                                                         | When                                                                                                 |
| --------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Shopify to pyck | Products, customers and orders                                       | Whenever the record changes in Shopify, and on demand for the whole catalogue                        |
| pyck to Shopify | Shipped orders with tracking, and stock counts if you switch that on | Whenever the warehouse reports a shipped order; stock on a timer or whenever pyck reports a movement |

Shopify stays the shop. pyck stays the warehouse. Neither replaces the other.

### Shopify to pyck

When you create or change a product, a customer or an order, Shopify tells the app, the app reads the current record from Shopify and writes it into pyck. Products arrive as items your pickers can find, orders arrive as picking orders. A product variant with no SKU is never sent, because pyck identifies stock by SKU.

Everything that comes from Shopify is kept together in one field of the pyck record, `shopify`, and replaced on every update. Fields your warehouse maintains in pyck stay as they are. See [What a sync overwrites in pyck](/shopify-app/data-mapping).

You can also send everything at once. The **Sync now** button on the Home page walks your whole store, which is how you bring an existing store over on day one.

### pyck to Shopify

When the warehouse has picked and packed an order, pyck calls the app and the app marks the order fulfilled in Shopify, with the tracking number if there is one. The customer gets their shipping email from Shopify as usual.

pyck can also drive your stock counts. This is off until you switch it on. See [Warehouse stock](/shopify-app/stock) for how that works and what it overwrites.

## What a connection is

A **connection** is one pyck tenant your store syncs to. You set up your first one during [setup](/shopify-app/setup), and it is called `production` — your real warehouse.

A store can have several connections at once, and you manage them under **Warehouses**: the list shows each one with its role and status, and each has its own page for everything you can change about it. That is how you run a test or staging tenant alongside the live one, or in place of it before go-live: it receives a copy of your data so you can try things against real records, but it never ships an order and never changes your stock. Customer names, emails, phone numbers and street lines are replaced with made-up ones in those copies. Only one connection can be the production connection, and only that one is allowed to fulfil orders, write stock back and receive your customers' real details.

To run a test tenant before you go live, see [Running a test tenant before go-live](/shopify-app/test-tenant).

Each connection has a short **label** — `production`, `stage`, `eu-prod` — and that label is how you steer individual products, customers and orders at one tenant rather than all of them. See [Sending data to several pyck tenants](/shopify-app/routing).

## Where to go next

* [Setup](/shopify-app/setup) — install the app and connect your first tenant.
* [What a sync overwrites in pyck](/shopify-app/data-mapping) — which fields Shopify owns, which pyck owns, and how files are handled.
* [Designing pyck schemas for Shopify](/shopify-app/schema-design) — for developers: naming schema fields so the app fills them without setup.
* [Sending data to several pyck tenants](/shopify-app/routing) — labels, and which tenant receives what.
* [Running a test tenant before go-live](/shopify-app/test-tenant) — try pyck on your real orders without shipping anything, then switch over.
* [Warehouse stock](/shopify-app/stock) — pairing locations, and letting pyck own your counts.
* [When something looks wrong](/shopify-app/troubleshooting) — symptoms and what they mean.


# Setup

Installing the Shopify app and connecting your first pyck tenant

Audience: Logistics Manager

Setting up is one step: connect one pyck tenant. Everything else on this page is optional and can wait.

## 1. Install the app

Install the pyck app into your Shopify store the way you install any Shopify app. Shopify will ask you to approve the permissions it needs — reading and writing products, customers, orders, draft orders, inventory and fulfilments, and reading locations.

After the install, the app opens on its **Setup** page, which greets you with "Welcome to pyck". It shows four steps, but only the first one is needed to finish setup. Until you finish it, nothing syncs.

## 2. Connect your first tenant

The Setup page asks for one pyck tenant. There are two ways to give it one.

### Sign in to pyck

Choose **Sign in to pyck**. You sign in to pyck in a new tab, come back, pick which of your pyck tenants this store belongs to and choose **Connect** with that tenant's name. A second tab opens to confirm. The app creates the credentials for you.

The app connects to pyck's production system unless you choose otherwise. To use a test or demo system instead, open **Connecting to a test or demo system?** first and pick it under **pyck system**.

This is the easier route and the one to use when your pyck system offers it.

### Paste an API key

If your pyck system has no sign-in registered, the app asks for an API key straight away. If it has one but the sign-in is not cooperating, choose **Have an API key instead?**. You then give the app two things:

* the pyck system, chosen under **Connecting to a test or demo system?**. If yours is self-hosted, choose **Other address…** and enter its full GraphQL address under **Address**.
* your pyck **API key**

Then choose **Connect with this key**.

Either way you end up with the same thing: one connection.

## 3. Setup is now complete

The connection you just made is called **production**. It is your live warehouse: the only connection that fulfils orders and the only one allowed to change your Shopify stock.

The name `production` is permanent. Routing labels point at that exact text, so it cannot be renamed later.

The moment it is saved:

* Setup is complete and the app's menu changes to **Home**, **Warehouses**, **Stock sync**, **Activity** and **Settings**.
* **Products, customers and orders are all switched on** under **Settings**, in the **Sync scope** card.
* **The warehouse itself starts switched off.** It receives nothing yet, so no store data reaches pyck before you have set it up.

Saving the connection gives pyck only what it needs to call back into your store: your callback details and the `shopify_config_v1` schema they are stored in. It does **not** create the schemas the app writes products, customers and orders into. Whether your tenant gets those is your decision, so the warehouse shows **Needs setup** under **Warehouses** at first.

To create them, open **Warehouses**, open the warehouse and choose **Check connection**. It creates the app's own schemas in the tenant and then checks the connection. Until you have done this, records sent to a warehouse in Auto mode fail in **Activity** with `DataType … not found`.

You can turn any of the three off under **Settings**, in the **Sync scope** card. Products and orders sync as you would expect; customers sync their profiles and also record the route labels their orders later inherit.

### Switch the warehouse on

Open **Warehouses** and open `production`. Its page starts with **Choose how this warehouse gets its schemas**. Answer it once:

* **Create the standard schemas** creates the standard Shopify schemas in your pyck tenant. Schemas that already exist there are left alone. Choose this unless your pyck tenant uses schemas of its own.
* **I'll map my own** creates nothing in pyck. You then connect your own schemas in the [data mapping](/shopify-app/data-mapping).

Switching on waits for this answer. Once it is given, choose **Switch on and go live…** under **Danger zone** and confirm. From then on products, customers and orders flow to pyck as they change in Shopify.

Until a warehouse is switched on, the app says so:

* **Home.** The banner you see after connecting says "Nothing is sent to pyck yet: a new warehouse starts switched off." **Needs you** lists each warehouse whose question is still open, for example "production is switched off until you choose how it gets its schemas.", with **Choose** to open that warehouse.
* **Warehouses.** While no warehouse is switched on, the banner says that production is switched off, "so nothing is sent to pyck and nothing comes back." If production's question is still open, it asks you to open production, choose how it gets its schemas, then switch it on.

Running setup again, or giving the warehouse a new key later, does not switch it on or off and does not ask the schema question again.

Product variants without a SKU are never sent. pyck finds stock by SKU, so a variant without one has nothing to match against.

## 4. Bring your existing catalogue over

New and changed records flow automatically, but records that already existed before you installed the app have never been sent. To send them once, choose **Sync now** on the **Home** page, or **Send everything now** in its **Set up pyck** checklist.

Run **Check connection** on the warehouse first (see above), or the records have no schema to go into.

This walks your whole store and sends everything currently switched on. **Activity** then lists what did not land. To see every attempt, including the successful ones, choose **Record every attempt** there.

### Choose how the warehouse gets its schemas

Before you send anything, open **Warehouses** and open the warehouse. Until it has an answer, its page starts with a card, **Choose how this warehouse gets its schemas**, with two answers:

* **Create the standard schemas** — the app creates its standard Shopify schemas in the pyck tenant and fills them. Schemas that already exist there are left as they are. Choose this unless your tenant has schemas of its own.
* **I'll map my own** — nothing is created in pyck. Set up the [data mapping](/shopify-app/data-mapping) next, before you send everything: the first send writes into whatever mapping is active. Until then, the **Data mapping** section of a switched-off warehouse reminds you to map your schemas before switching it on.

You answer once per warehouse. The card then goes away, and any later change goes through **Data mapping**. If the standard schemas cannot be created, the card shows why and stays, so you can try again. A warehouse without an API key is told to save one first, because the schemas are created in pyck.

A switched-off warehouse cannot be switched on while the question is open: its **Switch on** button under **Danger zone** is greyed out and says "Choose how this warehouse gets its schemas first."

### Check your Shopify metafields first

The first send fills only the metafields your production warehouse's schemas already carry. A metafield added afterwards gets its values only when the record next changes, or on the next full send. So before you send, the **Bring your catalog over** step offers **Check Shopify metafields**. It lists the metafields of your store that would not reach pyck (file metafields are uploaded anyway and are not listed). Products, customers or orders that use a custom mapping are left out, since there a metafield reaches pyck only through the mapping. For each one, choose:

* **Add** to add it to pyck's schemas, or **Add all** to add every listed field at once. Each add publishes a new version of the schema.
* **Keep out** for a field pyck should not receive, for example an internal or personal one. It is no longer offered or counted, and is listed under "Kept out of pyck" with **Bring back** to undo that. Keeping a field out changes nothing in pyck.

Nothing is added without you choosing it. The check is only offered when the production warehouse is switched on and has a key.

Run the send once after setup. After that, ordinary changes keep pyck up to date on their own.

## What is optional from here

Nothing below is required, and none of it is switched on by default.

| If you want to                                                                       | Go to                                                         |
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| Fill fields of your own pyck schemas from Shopify, or keep them under pyck's control | [What a sync overwrites in pyck](/shopify-app/data-mapping)   |
| Sync to more than one pyck tenant, or steer specific records at one tenant           | [Sending data to several pyck tenants](/shopify-app/routing)  |
| Let pyck own your Shopify stock counts                                               | [Warehouse stock](/shopify-app/stock)                         |
| Check a connection is healthy                                                        | **Warehouses**, open the warehouse, then **Check connection** |

Deleting your last connection reopens setup, and syncing stops until you connect one again.


# What a sync overwrites in pyck

Which fields a sync overwrites in pyck, which it leaves alone, and how files are handled

Audience: Logistics Manager

Every time a product, customer or order changes in Shopify, the app reads the current record from Shopify and updates the matching record in pyck. It changes only what comes from Shopify and leaves everything else on the record as it is.

Everything the app reads from Shopify goes into one field of the pyck record, called `shopify`. Fields you add to your own pyck schemas sit next to it and are filled only if you connect them to a Shopify source.

For example, a customer who has a mapped field `display_name` and a field `storage_zone` that is **Not synced** looks like this in pyck:

```json
{
  "shopify": { "firstName": "Anna", "lastName": "Becker", "...": "..." },
  "display_name": "Anna Becker",
  "storage_zone": "B-12"
}
```

`shopify` is the same whatever you map. A mapped field is an extra copy of a Shopify value, kept in the place you chose. It does not take the value out of `shopify`.

This page explains which fields count as "coming from Shopify", what happens when a value is cleared there, and how you keep a field under pyck's control.

## The rules at a glance

| Field                                                                                                         | Who decides     | What a sync does                                                                 |
| ------------------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------- |
| The `shopify` field: everything the app reads from Shopify (title, price, vendor, addresses, order totals, …) | Shopify         | Replaces it as a whole. A value Shopify no longer has disappears from it.        |
| A field you mapped to a Shopify source                                                                        | Shopify         | Overwrites it. If the value is cleared in Shopify, the field is removed in pyck. |
| A field set to **Not synced**                                                                                 | pyck            | Never touches it.                                                                |
| A field with no source, or any field your warehouse adds itself                                               | pyck            | Never touches it.                                                                |
| Files (product images, file metafields)                                                                       | Shopify, always | Replaced when the file changes in Shopify, deleted when it is deleted there.     |

In short: **Shopify owns the `shopify` field and what you connected to Shopify. pyck owns everything else. Files always follow Shopify.**

The same rules are shown in the app, in the banner **What a sync overwrites in pyck** when the data mapping is set to **Custom**.

## Where you choose a field's source

Open **Warehouses**, open the warehouse, and choose **Customise** in its **Data mapping** section (**Edit** once it is set to Custom). The mapping opens on a page of its own. With **Mapping mode** set to **Custom**, you pick a pyck schema for **Products**, **Customers** and **Orders**, and optionally for **Order lines**. The app lists every field of that schema except `shopify`. For each of those fields you choose where its value comes from:

| Source                                                | Takes the value from                                                        |
| ----------------------------------------------------- | --------------------------------------------------------------------------- |
| **Shopify field**                                     | A built-in Shopify field, such as the product's vendor or the order's total |
| **Shopify metafield**                                 | One of your metafields, for example `custom.color`                          |
| **Product tags** / **Customer tags** / **Order tags** | The record's tags, as a list                                                |
| **Product image** / **Shopify file metafield**        | A file (see [Files](#files) below)                                          |
| **Not synced**                                        | Nowhere. The field is maintained in pyck.                                   |

Choosing a source is a decision about **ownership**, not just about where a value is copied from. Once a field has a Shopify source, Shopify is in charge of it. The value is copied into your field in addition to `shopify`, not instead of it.

A field you leave without a source is **Not synced**. You can save the mapping that way.

Order lines have no metafields or tags in Shopify, so the fields of an order line schema cannot take a source: they are always **Not synced**, and the app writes only `shopify` on order lines.

Your schema must accept the `shopify` field, or the mapping cannot be saved. How to design schemas so that as few fields as possible need mapping is described in [Designing pyck schemas for Shopify](/shopify-app/schema-design).

The warehouse needs a saved API key, because the list of schemas comes from pyck. It does not need to be switched on: you can set up the mapping of a switched-off warehouse, so it is ready before any data reaches it.

## Fields with a Shopify source

A mapped field always mirrors Shopify.

**Example.** Your product schema has a field `color`, mapped to the metafield `custom.color`.

| In Shopify                               | In pyck after the sync              |
| ---------------------------------------- | ----------------------------------- |
| `custom.color` is set to `blue`          | `color` is `blue`                   |
| You change it to `red`                   | `color` is `red`                    |
| Someone edits `color` to `green` in pyck | The next sync sets it back to `red` |
| You delete the metafield `custom.color`  | `color` is removed from the record  |

Two things follow from this:

* **Changes made in pyck to a mapped field do not last.** The next time the record changes in Shopify, Shopify's value is written again. Make the change in Shopify instead.
* **Clearing a value in Shopify clears it in pyck.** If your warehouse needs the value to stay, the field should not be mapped. Set it to **Not synced**.

A metafield is cleared by deleting it. Some **Shopify fields** work differently: a text field you empty in the Shopify admin may still arrive as empty text, in which case the field stays in pyck with an empty value instead of being removed.

## Fields set to Not synced

A field set to **Not synced** belongs to pyck. The app never writes it and never removes it, whatever happens in Shopify.

Use it for anything your warehouse maintains: a storage zone, a pallet type, a handling note, a unit of measure that only matters on the shop floor.

**Example.** Your product schema has `palletType`, set to **Not synced**. Your team sets it to `EUR` in pyck. You then change the product's title, price and tags in Shopify. After each sync, `palletType` is still `EUR`.

**Switching a field to Not synced keeps its value.** If `ean` was mapped to a metafield and you switch it to **Not synced**, the value already in pyck stays, even if you later delete the metafield in Shopify. From then on, pyck owns it.

## Fields with no source, and your own fields

Fields with no source are **Not synced**: the app leaves them alone. This is also what happens when your pyck schema gains a new field that has not been mapped yet.

The same goes for anything your warehouse writes to a record that has no Shopify source. A workflow that stamps an order with a `status` or a hold reason keeps that value through every later order update from Shopify, as long as that field is not mapped to a Shopify source.

## The shopify field

Everything the app reads from Shopify (title, price, vendor, weight, addresses, order totals and so on) is written into one field of the record, `shopify`, under Shopify's own names, for example `shopify.product.title` or `shopify.shippingAddress.city`. It is owned by Shopify, whatever your mapping says.

On every sync the whole `shopify` field is replaced with what Shopify has now. A value Shopify no longer has is simply not in it any more. A note deleted on an order in Shopify, for example, disappears from the order in pyck.

Do not put warehouse information into `shopify`, and do not edit it in pyck: the next sync replaces it. Add a field of your own to the pyck schema and leave it **Not synced**.

## Files

Files are the one exception to "only what you mapped". **A file always follows Shopify**, whether you mapped it or not:

| In Shopify                                                               | In pyck after the sync                                                                                                              |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| You attach a file to a file metafield (e.g. an Amazon label on an order) | The file is attached to the record                                                                                                  |
| The same order syncs again with nothing changed                          | Still one file, no duplicates                                                                                                       |
| You swap the file for a new one                                          | The new file is attached and the old one is deleted                                                                                 |
| You clear the file metafield                                             | The file is deleted from the record                                                                                                 |
| You add an image to a product                                            | It is attached to the items of the variants it is assigned to in Shopify, or to every item of the product if it is assigned to none |
| You remove an image from a product                                       | The image is deleted from the item                                                                                                  |

Files your team attaches in pyck directly are never deleted by the app, even when Shopify's files change. The app only removes files it delivered itself. You recognise those by their description: `Shopify metafield <namespace.key>`, for example `Shopify metafield custom.amazon_labels`.

Single image files are supported. Other file types in a file metafield, such as PDFs, and metafields holding a list of files are not delivered yet. Files that were never delivered are not deleted either.

## When Shopify cannot be read

Shopify only tells the app *which* record changed. The app then reads the record from Shopify before it writes anything.

If that read fails, for example because Shopify is briefly unavailable or rate-limits the request, **nothing is written** and Activity shows a failed entry. The record in pyck stays exactly as it was, and the next change or a **Sync now** brings it up to date. If the record was deleted in Shopify before the app could read it, the sync is skipped with the reason "No longer exists in Shopify".

The same holds for fields with a Shopify source, for metafields in Auto mode and for files, which the app reads separately: if one of them cannot be read, it is **not** treated as cleared. The field or file stays exactly as it is in pyck, and the next successful sync brings it up to date.

A **metafield definition that no longer exists** is different. You pick metafields from a list, but if a definition is later deleted or renamed in Shopify, the mapping still names the old one and **Data mapping** marks it **Not defined in Shopify**. Shopify then answers normally and reports no such metafield on the record, so the app treats that as an empty value and **removes the field in pyck**. After deleting or renaming a metafield definition in Shopify, update the mapping before the next sync.

## Choosing between a Shopify source and Not synced

Ask who should be able to change the value.

| If                                                                                            | Then                                                                                                       |
| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| The value is maintained in the Shopify admin, and pyck should always show what the shop shows | Give it a Shopify source                                                                                   |
| The value is maintained by the warehouse, or set by a pyck workflow                           | Set it to **Not synced**                                                                                   |
| Both sides need to edit it                                                                    | Pick one owner. Edits on the other side are overwritten (Shopify source) or never reach pyck (Not synced). |

## Values pyck rejects

A mapped value is converted to the type your schema gives the field (a number, true or false, or text) and then has to fit it. If your schema only allows three characters and the Shopify source sends `POUNDS`, or expects a single value and the source sends a list of tags, pyck rejects the whole record. Nothing on it is updated, not even the fields that would have fit.

The same happens when your schema marks a mapped field as **required** and the value is cleared in Shopify: the app removes the field, pyck refuses a record without it, and the record stops updating until Shopify has a value again. Map required fields only to sources that are always filled, or set them to **Not synced**.

**Activity** shows a failed entry naming the field for orders, customers, new products and every record a **Sync now** run touches. When an existing product is updated because it changed in Shopify, a rejection only appears there after you choose **Record every attempt** on the Activity page.

**What to do.** Map the field to a source whose values fit, or set it to **Not synced**. For example, a product's **Weight unit** is not a unit of measure like `PCS`, and **Order tags** always arrive as a list.

**Metafields are the exception.** A metafield arrives in the shape Shopify stores it. A list metafield is a list, and a weight, dimension, rating, money or link metafield is a group of values, such as a number with its unit (`2.5` `KILOGRAMS`). If the field it is mapped to cannot hold that shape, for example a weight mapped to a plain number field, the app **leaves that one value out and removes it from the field in pyck**. The rest of the record is still updated. Whoever maintains your schemas can declare the field in the right shape; see [Metafield value shapes](/shopify-app/schema-design#metafield-value-shapes).

A schema that does not accept the `shopify` field would make every sync fail. Data mapping refuses to save it and says which schema needs `"shopify": { "type": "object" }` added.

## Connections in Auto mode

With **Mapping mode** set to **Auto**, there is no per-field mapping: the app fills its standard Shopify schemas, and the record carries only `shopify`. To bring your own metafields along, use **Check** in the **Shopify metafields** block of **Data mapping**. It lists each metafield the schemas do not carry yet, with **Add** to add that one and **Add all** to add every listed field. Choose **Keep out** for a field pyck should not receive: it is no longer raised as not synced, and **Bring back** undoes that. The kept-out list is stored by the app for this warehouse and nothing is written to pyck. The values of added metafields arrive inside `shopify`, under `shopify.metafields`, for example `shopify.metafields.custom.material`. They follow Shopify and disappear in pyck when the metafield is deleted in Shopify. Lists arrive as lists, and a weight or other measurement keeps its unit, for example `{ "value": 2.5, "unit": "KILOGRAMS" }`. A weight, dimension, volume or rating metafield added with an earlier version of the app was not accepted by pyck; adding any metafield with **Add** or **Add all** also corrects those, and their values arrive from the next sync on. File metafields are not added to the schemas: they are attached to the record as files, and follow Shopify here too.

## Related pages

* [Setup](/shopify-app/setup): connecting your first tenant.
* [Sending data to several pyck tenants](/shopify-app/routing): which tenant receives what.
* [When something looks wrong](/shopify-app/troubleshooting): symptoms and what they mean.


# Designing pyck schemas for Shopify

How to design pyck schemas so the Shopify app can write into them, and how to name the fields you add

Audience: Programmer

If a pyck tenant will be connected to a Shopify store, now or later, design its schemas (DataTypes) for items, customers, picking orders and order lines around the way the Shopify app writes. The app puts everything it reads from Shopify into one object field, `shopify`. Every other field of the schema is yours: the app leaves it alone unless someone gives it a Shopify source in the app's Data mapping.

This page is for whoever designs the tenant's schemas, whether that is the customer's own developer or the pyck team.

{% hint style="info" %}
**The short version.** Let your schema accept `shopify` as an object. Read Shopify's data from `data.shopify` instead of declaring your own copy of it. Give warehouse-only data names of your own. For values held in Shopify metafields, name the pyck field after the metafield key.
{% endhint %}

## How the app writes a record

Every record the app writes has a `data` object with up to three kinds of content:

| Content                                               | Who writes it                | On every sync                                             |
| ----------------------------------------------------- | ---------------------------- | --------------------------------------------------------- |
| `data.shopify`                                        | The app                      | Replaced as a whole with what Shopify has now             |
| A field mapped to a Shopify source (Custom mode only) | The app                      | Overwritten; removed when the value is cleared in Shopify |
| Every other field                                     | Your warehouse and workflows | Never touched                                             |

There is one exception. When a line is removed from an order in Shopify, the app deletes the whole order line in pyck, including your fields on it. See [Lines removed by an order edit](#lines-removed-by-an-order-edit).

Your own fields sit **next to** `shopify` at the top level of `data`, never inside it. A customer record in a tenant that maps `display_name` to the Shopify field **Display name** and keeps `storage_zone` for the warehouse looks like this:

```json
{
  "shopify": { "id": "gid://shopify/Customer/6987654321", "firstName": "Anna", "lastName": "Becker" },
  "display_name": "Anna Becker",
  "storage_zone": "B-12"
}
```

`data.shopify` is the same whatever you map. Mapping a field never moves a value out of it and never adds one to it: the mapped field is an additional copy, in the place and type you chose. A field without a source never receives anything from Shopify.

`data.shopify` holds the Shopify record as Shopify's Admin GraphQL API returns it:

* **Shopify's own field names and nesting**, in camelCase: `shopify.product.title`, `shopify.inventoryItem.measurement.weight`, `shopify.shippingAddress.city`.
* **Lists are plain arrays.** Where the API wraps a list in `edges { node }`, the app unwraps it.
* **Empty values are left out.** A field Shopify returns as `null` does not appear, and an object left with nothing in it disappears too. Empty lists stay (`"tags": []`).
* **Values are not converted.** Money stays a string (`"89.95"`), enums stay in Shopify's upper case (`ACTIVE`, `PAID`, `GRAMS`).

The app finds a record again by what it wrote there: an item by its `sku` (pyck's own field, not part of `data`), a customer, a picking order and an order line by `data.shopify.id`, and all items of a product by `data.shopify.product.id`.

Never write into `data.shopify` from pyck. The next sync replaces it, and a record whose `shopify.id` is gone is not found again and is created a second time.

## Auto and Custom mode

Every warehouse's page under **Warehouses** has a **Data mapping** section. It shows **Standard** while the mode is Auto, and **Customise** opens the mapping page with its **Mapping mode**. Until the warehouse's schema question (see below) is answered, the section shows **Not chosen yet** instead and has no **Customise** button:

| Mode       | What pyck receives                                                                                                                                                                                                                                                                                                                                                                |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Auto**   | The app's own schemas `shopify_item_v1`, `shopify_customer_v1`, `shopify_order_v1`, `shopify_order_item_v1`, `shopify_file_v1` and `shopify_config_v1`, which the app creates and fills. Adding a warehouse creates only `shopify_config_v1`, which holds the callback details pyck needs. The others are created when someone runs **Check connection** on the warehouse's page. |
| **Custom** | A schema you pick from the tenant for products, customers and orders, and optionally for order lines. Order lines without a schema of their own go into `shopify_order_item_v1`.                                                                                                                                                                                                  |

Each warehouse starts with a one-time question on its page, **Choose how this warehouse gets its schemas**, and cannot be switched on until it is answered. **Create the standard schemas** selects Auto and creates the app's schemas in the tenant, leaving existing ones alone. **I'll map my own** selects Custom and creates nothing, so the mapping has to be set up next.

If the tenant needs no fields beyond what Shopify has, use **Auto** and stop reading here. Metafields can be added in Auto mode too (see [Values from metafields](#values-from-metafields)).

## Your schema must accept the shopify field

Every sync writes `data.shopify`, and pyck checks the whole `data` against your schema. Either:

* declare `"shopify": { "type": "object" }`, or
* leave `additionalProperties` open (it is by default).

Data mapping refuses a schema that declares `shopify` as anything other than an object, or that leaves it out while setting `additionalProperties: false`. The message reads, for example, `DataType "item_v2" does not allow the "shopify" key the app writes — add "shopify": { "type": "object" } to its properties`.

You can mark `shopify` as **required**: the app always writes it.

Declare as little as possible inside `shopify`. `{ "type": "object" }` is enough. If you do describe its contents, use Shopify's types (money as `string`, enums in upper case), keep `additionalProperties` open inside it, and do not mark anything inside it as required or restrict it with `enum`, `pattern`, `maxLength` or `format`. A value Shopify does not have is left out, and Shopify adds fields over time.

## What the shopify field contains

### Items (products)

One pyck item per Shopify **variant**. Variants without a SKU are never sent. The item's SKU is pyck's own `sku` field.

| Path                                                                              | Content                                                                       |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `id`                                                                              | Variant ID (`gid://shopify/ProductVariant/…`)                                 |
| `title`, `displayName`                                                            | Variant title (`White`), and product plus variant (`Bloom Desk Lamp - White`) |
| `sku`, `barcode`                                                                  |                                                                               |
| `price`, `compareAtPrice`                                                         | Strings, e.g. `"89.95"`                                                       |
| `position`, `inventoryQuantity`                                                   | Integers                                                                      |
| `inventoryPolicy`                                                                 | `DENY` or `CONTINUE`                                                          |
| `taxable`                                                                         | Boolean                                                                       |
| `selectedOptions`                                                                 | List of `{ name, value }`                                                     |
| `inventoryItem.requiresShipping`, `.harmonizedSystemCode`, `.countryCodeOfOrigin` |                                                                               |
| `inventoryItem.measurement.weight`                                                | `{ value, unit }`, unit e.g. `GRAMS`, `KILOGRAMS`, `OUNCES`, `POUNDS`         |
| `createdAt`, `updatedAt`                                                          | ISO 8601 date-time                                                            |
| `product.id`                                                                      | Product ID (`gid://shopify/Product/…`)                                        |
| `product.title`, `.handle`, `.descriptionHtml`, `.vendor`, `.productType`         |                                                                               |
| `product.status`                                                                  | `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED`                                   |
| `product.tags`                                                                    | List of strings                                                               |
| `product.publishedAt`, `.createdAt`, `.updatedAt`                                 |                                                                               |
| `metafields.<namespace>.<key>`                                                    | Auto mode only: metafields added to the schema                                |

The app reads up to 100 variants and 100 images per product.

### Customers

| Path                               | Content                                              |
| ---------------------------------- | ---------------------------------------------------- |
| `id`                               | Customer ID (`gid://shopify/Customer/…`)             |
| `firstName`, `lastName`            |                                                      |
| `defaultEmailAddress.emailAddress` |                                                      |
| `defaultPhoneNumber.phoneNumber`   |                                                      |
| `state`                            | e.g. `ENABLED`                                       |
| `verifiedEmail`, `taxExempt`       | Booleans                                             |
| `tags`                             | List of strings                                      |
| `note`                             |                                                      |
| `defaultAddress`                   | Address object, with its `id`                        |
| `addresses`                        | List of up to 10 address objects, each with its `id` |
| `createdAt`, `updatedAt`           |                                                      |
| `metafields.<namespace>.<key>`     | Auto mode only                                       |

An address object contains `firstName`, `lastName`, `company`, `address1`, `address2`, `city`, `province`, `provinceCode`, `country`, `countryCodeV2`, `zip` and `phone`.

### Picking orders (orders)

| Path                                                                                             | Content                                                       |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| `id`                                                                                             | Order ID (`gid://shopify/Order/…`)                            |
| `name`, `number`                                                                                 | `#1001` and `1001`                                            |
| `email`, `phone`, `poNumber`, `note`                                                             |                                                               |
| `customer.id`                                                                                    | Customer ID; absent on guest orders                           |
| `displayFinancialStatus`, `displayFulfillmentStatus`                                             | e.g. `PAID`, `UNFULFILLED`                                    |
| `currencyCode`                                                                                   | e.g. `EUR`                                                    |
| `totalPriceSet`, `subtotalPriceSet`, `totalTaxSet`, `totalDiscountsSet`, `totalShippingPriceSet` | `{ shopMoney: { amount, currencyCode } }`, amount as a string |
| `taxesIncluded`, `test`                                                                          | Booleans; `test` marks a Shopify test order                   |
| `shippingAddress`, `billingAddress`                                                              | Address objects, without `id`                                 |
| `tags`                                                                                           | List of strings                                               |
| `statusPageUrl`                                                                                  |                                                               |
| `processedAt`, `cancelledAt`, `closedAt`, `createdAt`, `updatedAt`                               |                                                               |
| `metafields.<namespace>.<key>`                                                                   | Auto mode only                                                |

### Order lines

One pyck picking order item per Shopify line item that has a SKU, a variant and a current quantity above 0, up to 100 per order. pyck's own `quantity` field holds the line's **current** quantity (`currentQuantity`). Units an order edit removed are not included.

| Path                                             | Content                                                                                                    |
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `id`                                             | Line item ID (`gid://shopify/LineItem/…`)                                                                  |
| `name`, `title`, `variantTitle`, `sku`, `vendor` |                                                                                                            |
| `quantity`                                       | Integer: units ordered originally, including units since removed or refunded                               |
| `currentQuantity`                                | Integer: units still ordered, with removed and refunded units left out. Same as the line's pyck `quantity` |
| `unfulfilledQuantity`                            | Integer                                                                                                    |
| `taxable`, `requiresShipping`                    | Booleans                                                                                                   |
| `originalUnitPriceSet`, `totalDiscountSet`       | `{ shopMoney: { amount, currencyCode } }`                                                                  |
| `variant.id`, `product.id`                       |                                                                                                            |

#### Lines removed by an order edit

Shopify does not delete a line when someone removes it from an order with an order edit. The line stays on the order with a `currentQuantity` of 0. The app treats that line as no longer ordered and does not sync it.

When an existing picking order syncs, from a webhook or from **Sync now**, the app first writes the lines that are still on the order. It then **deletes** every line of that picking order whose `data.shopify.id` is no longer among the order's current lines in Shopify. Anything your workflow wrote on a deleted line is deleted with it. A line is not set to quantity 0. It is removed.

* **Lines without `data.shopify.id` are kept.** These are lines your workflow added to the picking order itself.
* **Lines that are still ordered are kept, even if they cannot be synced.** For example, a line without a SKU is not written, but a pyck line that already exists for it is not deleted.
* **Nothing is deleted on orders with more than 100 lines.** The app reads the first 100 lines of an order. If the order has more, a line missing from the read may still be on the order, so the app deletes nothing.
* **A failed delete makes the sync partial**, the same as a line that fails to write. When an order update from Shopify deletes lines, Activity records it with the number of lines removed (`itemsRemoved`), even if nothing failed.

{% hint style="warning" %}
The app also deletes a removed line that the warehouse has already picked. If your workflow needs to react to a removed line, for example to put picked goods back, it must not depend on that line still existing in pyck.
{% endhint %}

### Files (product images)

Product images are pyck files attached to the items, with `data` of the form `{ "shopify": { "id", "alt", "image": { "url", "width", "height" } } }`. The `id` is Shopify's `MediaImage` ID.

## Your own fields

In Custom mode, Data mapping lists every field of your schema except `shopify` as an **extra field**. Each one can take a source:

| Source                                                | Takes the value from                                                                          |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| **Shopify field**                                     | A field of the Shopify record, from the app's list (see [below](#shopify-fields-you-can-map)) |
| **Shopify metafield**                                 | A metafield with a definition in Shopify                                                      |
| **Product tags** / **Customer tags** / **Order tags** | The record's tags, as a list                                                                  |
| **Product image** / **Shopify file metafield**        | A file (file fields only)                                                                     |
| **Not synced**                                        | Nowhere                                                                                       |

A field without a source is **Not synced**: the app never writes it and never removes it. A mapping can be saved with fields left that way.

Order line schemas are the exception: a Shopify order line has no metafields or tags, so every extra field of an order line schema is **Not synced**.

### Do you need a field of your own?

Everything in [`data.shopify`](#what-the-shopify-field-contains) is already on the record. A workflow or a pyck screen that needs the vendor reads `data.shopify.product.vendor`. It does not need a `vendor` field.

Add a field of your own when:

* the value is **not in `data.shopify`**: a metafield, or one of the Shopify fields listed under [Shopify fields that are not in the shopify field](#shopify-fields-that-are-not-in-the-shopify-field);
* your workflow or UI needs a value **at a different place or in a different type**, e.g. a flat `weight_kg` as a number;
* the value is **warehouse data** Shopify does not have.

A mapped field holding a value that is also in `data.shopify` stores it twice. That is fine when you need it there, but both copies follow Shopify. Neither is a place to change the value.

### Types

A mapped value is converted to the type your schema declares for the field: `number` and `integer` become numbers, `boolean` becomes `true` or `false`, `string` becomes text. A field `price` of type `number` mapped to the Shopify field **Price** therefore receives `89.95`, while `data.shopify.price` keeps `"89.95"`. A value that cannot be converted (text into a number) is written unconverted, and pyck rejects the record if the type does not allow it.

Tags always arrive as a list. A field filled from tags must be an `array` of strings.

### The Auto-map button

The **Auto-map same names** button fills in a source for each extra field that has no source yet or is set to **Not synced**, by looking for a Shopify value of the same name in two places:

* the **Shopify fields** the app can read, named by their path in Shopify's Admin GraphQL API (`inventoryPolicy`, `product.seo.title`, `inventoryItem.harmonizedSystemCode`, `poNumber`, `numberOfOrders`, …);
* the store's **metafields**, by key without the namespace (`ean` ← `custom.ean`). Metafields in the app's own `app--…` namespaces are skipped.

The comparison:

* **camelCase and snake\_case are the same name.** A pyck field `harmonized_system_code` inside an object `inventory_item` matches Shopify's `inventoryItem.harmonizedSystemCode`, and so does `inventoryItem.harmonizedSystemCode`. Upper and lower case are ignored as well (`EAN` matches `custom.ean`). Nothing else is folded together: no synonyms, no abbreviations, no hyphens.
* **Paths are compared whole.** An object field must have the same name as Shopify's object: `inventory_item.country_code_of_origin` matches, `origin.country` does not.
* **One candidate or nothing.** If two sources fit (e.g. `custom.ean` and `erp.ean`, or a Shopify field and a metafield of the same name), the field is left for you to choose.
* **The type is not compared.** A text field can be matched to a numeric Shopify value. Check the result.
* **Only a suggestion.** The result is shown in the list and only takes effect when you save. Someone still has to open Data mapping on every store and press the button.

### Shopify fields you can map

| Entity    | Shopify fields                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Items     | `sku`, `barcode`, `price`, `compareAtPrice`, `taxable`, `inventoryPolicy`, `position`, `title`, `displayName`, `inventoryItem.measurement.weight.value`, `inventoryItem.measurement.weight.unit`, `inventoryItem.requiresShipping`, `inventoryItem.harmonizedSystemCode`, `inventoryItem.countryCodeOfOrigin`, `product.title`, `product.handle`, `product.vendor`, `product.productType`, `product.status`, `product.descriptionHtml`, `product.description`, `product.createdAt`, `product.updatedAt`, `product.publishedAt`, `product.onlineStoreUrl`, `product.totalInventory`, `product.hasOnlyDefaultVariant`, `product.isGiftCard`, `product.seo.title`, `product.seo.description` |
| Customers | `firstName`, `lastName`, `displayName`, `email`, `phone`, `note`, `locale`, `state`, `taxExempt`, `verifiedEmail`, `numberOfOrders`, `amountSpent.amount`, `amountSpent.currencyCode`, `createdAt`, `updatedAt`, `emailMarketingConsent.marketingState`, `smsMarketingConsent.marketingState`, and the `defaultAddress.…` fields                                                                                                                                                                                                                                                                                                                                                          |
| Orders    | `name`, `email`, `phone`, `note`, `poNumber`, `currencyCode`, `presentmentCurrencyCode`, `displayFinancialStatus`, `displayFulfillmentStatus`, `confirmed`, `closed`, `cancelledAt`, `cancelReason`, `processedAt`, `createdAt`, `updatedAt`, `test`, `taxesIncluded`, `sourceName`, `totalPriceSet.shopMoney.amount`, `subtotalPriceSet.shopMoney.amount`, `totalTaxSet.shopMoney.amount`, `totalDiscountsSet.shopMoney.amount`, `totalShippingPriceSet.shopMoney.amount`, `totalWeight`, and the `shippingAddress.…` and `billingAddress.…` fields                                                                                                                                      |

The address fields are `firstName`, `lastName` and `name` (order addresses only), `company`, `address1`, `address2`, `addressLines`, `city`, `province`, `provinceCode`, `country`, `countryCodeV2`, `zip` and `phone`. `addressLines` is address line 1 and 2 joined with a comma, for a pyck field that has room for only one street line.

Values Shopify calls something else, or that the app cannot read at all, need a source chosen by hand or have none: an item's `cost` has no Shopify field, a customer's `orders_count` is `numberOfOrders` in Shopify, and `total_spent` is `amountSpent.amount`.

### Shopify fields that are not in the shopify field

These can only reach pyck through a field of your own:

| Entity    | Fields                                                                                                                                                                                        |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Items     | `product.description` (plain text), `product.onlineStoreUrl`, `product.totalInventory`, `product.hasOnlyDefaultVariant`, `product.isGiftCard`, `product.seo.title`, `product.seo.description` |
| Customers | `displayName`, `email`, `phone`, `locale`, `numberOfOrders`, `amountSpent.amount`, `amountSpent.currencyCode`, `emailMarketingConsent.marketingState`, `smsMarketingConsent.marketingState`   |
| Orders    | `presentmentCurrencyCode`, `confirmed`, `closed`, `cancelReason`, `sourceName`, `totalWeight`                                                                                                 |

### Values from metafields

If a value lives in a Shopify metafield, name the pyck field **after the metafield key**, without the namespace. **Auto-map same names** then connects them in one click. The metafield needs a definition in Shopify (**Settings → Custom data**), and for items it must be a **product** metafield: variant metafields are not offered.

| Metafield in Shopify   | pyck field                        | Result                                                                        |
| ---------------------- | --------------------------------- | ----------------------------------------------------------------------------- |
| `custom.ean`           | `ean`                             | Mapped automatically                                                          |
| `custom.pallet_height` | `pallet_height` or `palletHeight` | Mapped automatically (camelCase and snake\_case are treated as the same name) |
| `custom.ean`           | `ean_code`                        | Not mapped; choose the source by hand                                         |

In **Auto** mode there are no fields of your own. Instead, the **Shopify metafields** block in Data mapping checks which metafields of the store the schemas do not carry yet. **Add** (per field) or **Add all** declares them in the app's schemas, and **Keep out** leaves a field out of pyck for good. Their values then arrive at `data.shopify.metafields.<namespace>.<key>`, e.g. `data.shopify.metafields.custom.material`.

#### Metafield value shapes

The app writes a metafield value in the shape Shopify stores it. Lists become arrays, and measurements, ratings, money and links become objects, so a weight keeps its unit. Declare a field filled from a metafield with the matching type:

| Shopify metafield type                                                                                                                                | Declare the pyck field as                                        | Example value                                                |
| ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------ |
| `number_integer`, `number_decimal`                                                                                                                    | `number`                                                         | `12.5`                                                       |
| `boolean`                                                                                                                                             | `boolean`                                                        | `true`                                                       |
| Text, date, URL, color, references and other single values                                                                                            | `string`                                                         | `"Cotton"`                                                   |
| Measurements: `weight`, `volume`, `dimension`, `temperature` and the other unit-based types (`distance`, `duration`, `energy`, `power`, `voltage`, …) | `object` with `value` (`number`) and `unit` (`string`)           | `{ "value": 2.5, "unit": "KILOGRAMS" }`                      |
| `rating`                                                                                                                                              | `object` with `value`, `scale_min`, `scale_max` (all `number`)   | `{ "value": 3.5, "scale_min": 1, "scale_max": 5 }`           |
| `money`                                                                                                                                               | `object` with `amount` (`number`) and `currency_code` (`string`) | `{ "amount": 5.99, "currency_code": "EUR" }`                 |
| `link`                                                                                                                                                | `object` with `text` and `url` (both `string`)                   | `{ "text": "Data sheet", "url": "https://…" }`               |
| `list.<type>`                                                                                                                                         | `array` whose `items` have the shape of `<type>` above           | `["red", "blue"]`, `[{ "value": 2.5, "unit": "KILOGRAMS" }]` |

Numbers Shopify stores as text inside an object or list, such as a rating's `"3.5"`, are converted to numbers when the member or `items` is declared as `number`. A field declared as `string` receives the value as JSON text instead, e.g. `{"value":2.5,"unit":"KILOGRAMS"}`.

A value that does not fit the declared type is **left out** instead of making pyck reject the whole record. A weight mapped to a field declared as `number`, or a list that is not valid JSON, is removed from that field in pyck, and the rest of the record is still written.

In Auto mode the app declares these shapes itself. Earlier versions of the app declared measurements and ratings as `number`, which no Shopify value fits. Those declarations are corrected to the shapes above the next time the app republishes its schemas, for example when any metafield is added with **Add** or **Add all** in the **Shopify metafields** block.

### Files

A field of type file (e.g. a shipping label stored in a file metafield) is named after the metafield key in the same way. File fields must be at the top level of the schema. Inside an object, they are not delivered. Product images can be mapped to any file field on the item schema.

Files from file metafields are attached to the record in both modes, whether a field is mapped to them or not. See [What a sync overwrites in pyck](/shopify-app/data-mapping#files).

### Warehouse-only data

Fields only the warehouse maintains (storage zone, pallet type, handling notes, a workflow status) need no Shopify counterpart. Give them names of your own and leave them without a source. The app then never touches them. See [What a sync overwrites in pyck](/shopify-app/data-mapping#fields-set-to-not-synced).

### Nested objects

An object field of your own (e.g. `delivery_address`) is listed in Data mapping one sub-field at a time, up to three levels deep, and each sub-field gets its own source. Auto-map compares the whole path, so `delivery_address.city` is not picked up, because Shopify calls that address `shippingAddress`.

The order's addresses are already in `data.shopify.shippingAddress` and `data.shopify.billingAddress`. Add an address object of your own only if your workflow needs the address in another place or shape.

## Types must match

pyck validates every record against its schema. If one value does not fit, pyck rejects the **whole record** and nothing on it is updated. Activity shows a failed entry such as `jsonschema validation failed: at '/weight_kg': got string, want number`.

Typical mistakes:

| Mistake                                                                                                  | Correct                                                                                 |
| -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `shopify` declared as `string`, or missing while `additionalProperties` is `false`                       | `"shopify": { "type": "object" }`                                                       |
| Sub-fields of `shopify` declared with your own types, e.g. `price` as `number`                           | Leave `shopify` undeclared inside, or use Shopify's types (`price` is a string)         |
| A field filled from tags declared as `string`                                                            | `array` of strings                                                                      |
| A field filled from a weight or other measurement metafield declared as `number` (the value is left out) | `object` with `value` and `unit`, see [Metafield value shapes](#metafield-value-shapes) |
| A mapped field marked `required` that Shopify can leave empty                                            | Not required, or a source that always has a value                                       |
| A short `maxLength` on a mapped field, e.g. a weight unit (`POUNDS`) into a three-character unit field   | A source whose values fit, or no limit                                                  |

Rules for the schema as a whole:

* **Leave `additionalProperties` open**, or at least declare `shopify`. The app's own schemas are open for the same reason.
* **Mark only `shopify` and your own warehouse fields as required**, and only fields that always have a value. A mapped field whose value is cleared in Shopify is removed, and a required field without a value makes pyck reject the record.
* **Do not restrict mapped fields** with `maxLength`, `minLength`, `pattern`, `format` or your own `enum` unless every Shopify value fits.

## Example

An item schema for a tenant that extends Shopify's data with an EAN from a metafield and two warehouse fields:

```json
{
  "type": "object",
  "required": ["shopify"],
  "properties": {
    "shopify":      { "type": "object", "description": "Written by the Shopify app" },

    "ean":          { "type": "string", "description": "From metafield custom.ean" },
    "storage_zone": { "type": "string", "description": "Maintained in pyck" },
    "pallet_type":  { "type": "string", "enum": ["EUR", "ONEWAY"], "description": "Maintained in pyck" }
  }
}
```

In Data mapping, this schema shows exactly three extra fields. **Auto-map same names** connects `ean` to `custom.ean`. `storage_zone` and `pallet_type` have no source and stay **Not synced**. Title, price, vendor and everything else Shopify knows are read from `data.shopify` (`shopify.product.title`, `shopify.price`, `shopify.product.vendor`) without any setup.

## Schemas from before the shopify field

Up to October 2026, the app wrote Shopify data as top-level snake\_case keys (`shopify_id`, `title`, `price`, `shipping_address`, …) and filled schema fields with those names on its own. It no longer does. In a schema designed for that:

* those fields are now extra fields like any other. Without a source they are **Not synced** and keep their last value forever;
* the schema has to accept `shopify` before Data mapping saves it.

To move a tenant over, remove the old keys from the schema (or give them a source if a workflow still reads them), make sure it accepts `shopify`, run **Check connection** on the warehouse's page under **Warehouses** so the app's own schemas are updated, and send everything again with **Sync now** on the Home page.

Items are found again by their SKU and updated; their old keys stay next to `shopify` until you remove them. Customers, picking orders and order lines synced before carry no `data.shopify.id`, so the new sync does not find them and creates them again. Remove them from pyck before you send everything, or they exist twice.

## Checklist

Before connecting a tenant to Shopify, check each schema for:

* [ ] `shopify` is declared as an object, or `additionalProperties` is not `false`.
* [ ] Nothing inside `shopify` is required or restricted.
* [ ] No field of your own copies a value that is already in `data.shopify`, unless a workflow needs it there.
* [ ] Mapped fields have types the Shopify value converts to; fields filled from tags are arrays.
* [ ] Only `shopify` and fields that always have a value are required.
* [ ] Fields filled from metafields are named after the metafield key.
* [ ] File fields are at the top level.
* [ ] Warehouse-only fields have their own names and no source.

## Related pages

* [What a sync overwrites in pyck](/shopify-app/data-mapping): who owns which field once the mapping is set.
* [When something looks wrong](/shopify-app/troubleshooting#a-record-fails-with-jsonschema-validation-failed): records rejected by pyck.
* [Setup](/shopify-app/setup): connecting a tenant.


# Sending data to several pyck tenants

Directing products, customers and orders at particular pyck tenants

Audience: Logistics Manager

One Shopify store can sync to several pyck tenants at once — a live warehouse and a test tenant, or two warehouses in different regions. Each of them is a **connection**, and each connection has a short **label** such as `production`, `stage` or `eu-prod`.

By default every tenant gets everything. Labels are how you narrow that down.

## The default: everything goes everywhere

A product, customer or order that carries no label at all is **broadcast** — delivered to every connection that is switched on and accepts broadcast.

That is the right behaviour most of the time. If you only have one connection, this is all that ever happens and you can stop reading here.

If no switched-on connection accepts broadcast, a record without a label goes nowhere: the sync fails and Activity says "No active pyck connection accepts broadcast entities."

## Narrowing with a label

Put a label on a record and it stops broadcasting. It goes to exactly the connections you named, and nowhere else. Naming a connection reaches it even if that connection has broadcast switched off.

There are two ways to write a label, and you can use either.

| Way                      | Where you set it                                                                                                          | Looks like         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| The **pyck route** field | The pyck route field on the product, customer or order page in the Shopify admin. It is a list, so you can enter several. | `stage`            |
| A **tag**                | The record's tags                                                                                                         | `pyck-route-stage` |

Both do the same job. Use whichever fits how you already work — the field is easier to read at a glance, tags are easier to apply in bulk. Upper and lower case do not matter in either.

## The two ways add up — neither overrules the other

This is the part that surprises people.

The two signals are **combined**, not ranked. A record carrying the field `stage` and the tag `pyck-route-demo` goes to **both** `stage` and `demo`.

There is no way to say "ignore the tag, use the field". To stop a record reaching a tenant, remove the label that names it. Adding a different label somewhere else only adds a destination.

### Orders also inherit from their customer

An order also goes wherever its customer's labels point:

* the customer's `pyck-route-…` tags, read together with the order;
* the labels recorded for the customer the last time that customer synced. This is how the customer's **pyck route** field reaches the order.

So an order tagged `pyck-route-demo`, placed by a customer labelled `stage`, is delivered to **both**. Again, they add up.

Two things follow from this. A customer's pyck route field only reaches their orders after the customer has synced, so it does not work while customer sync is switched off. And a label on the customer that matches no connection stops every order of that customer, just like a label on the order itself.

## A label nobody recognises stops the sync

If you write a label that matches no connection on your store — a typo like `pyck-route-stagg`, or a connection that was deleted — the record **does not sync at all**. It is not partially delivered, and it does not quietly fall back to broadcast.

That is deliberate. You wrote a label because you wanted to restrict where the record goes. Treating an unrecognised label as "send it everywhere" would do the exact opposite of what you asked for and put your data in tenants you meant to exclude. Failing loudly is the safer answer.

The same applies to a label that names a connection you have switched off: the sync fails and says so, rather than delivering somewhere you did not name.

You will see the failure in **Activity**, with the offending label named: "Unknown pyck route label(s): …" or "Inactive pyck connection(s) named: …". Fix the label and the record syncs on its next change, or choose **Sync now** on the Home page.

A pyck route field the app cannot read, or one with an empty entry, stops the sync in the same way, with a message that the field "could not be resolved".

## Being sent an order and shipping it are different things

Several tenants can hold the same order. Only the production connection may ship it, and only if the order was sent to it.

Every time an order syncs, the app writes down which connections it was sent to. That list replaces the one from the order's previous sync. When a tenant reports an order as shipped, two things are checked:

1. The tenant is your switched-on production connection. Every other tenant holding the order has a copy, so it can display the order or test against it, but it can never ship it. If it tries, it is refused.
2. The order's last sync sent it to production. If it did not, production is refused too.

This is what stops one order being packed and posted twice, and what keeps a test tenant from marking one of your real orders as shipped.

An order that was last synced while production was switched off was not sent to production, so **nobody can ship it**. That is the normal state of every order while production is switched off, which is how you run a test tenant before going live. See [Running a test tenant before go-live](/shopify-app/test-tenant). The same goes for an order the app has never synced. Production can ship such an order once it syncs again with production switched on: change the order, or choose **Sync now** on the Home page.

Because each sync replaces the list, this also works the other way round. If you switch production off and an order then changes, that sync does not reach production, and production cannot ship that order until it syncs again with production switched on.

{% hint style="warning" %}
**Make production lets the new production connection ship orders it received as a copy.** Shipping depends only on which connection is production *now*, and on which connections the order was sent to. A tenant that received an order as a copy can ship it as soon as you make it production, even if your previous production warehouse is still picking that order. Before you choose **Make production**, agree with your team which warehouse finishes the orders that are already open.
{% endhint %}

While Shopify locations are paired with the current production tenant's storage areas, **Make production** and **Make test copy** are refused until you remove those pairings. See [Warehouse stock](/shopify-app/stock#1-pair-each-location-with-a-storage-area).

## Test orders never reach production

An order Shopify marks as a test — placed through the Bogus gateway or Shopify Payments test mode — is excluded from the production connection no matter what labels it carries. It still reaches your other tenants, which is usually the point of placing it. Because it never reaches production, nobody can ship it.

If production is the only place a test order would go — for example on a store with a single connection — it goes nowhere, and Activity shows a failed sync: "Every routed connection was excluded by the test-order rule."

## Only production writes stock back

Stock only ever travels back to Shopify from the production connection. A staging or demo tenant's quantities are not real, and two tenants writing the same Shopify numbers would overwrite each other. See [Warehouse stock](/shopify-app/stock).

## Summary

| Situation                                                 | Where it goes                                                                                                            |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| No label anywhere                                         | Every switched-on connection that accepts broadcast                                                                      |
| No label, and no switched-on connection accepts broadcast | Nothing — the sync fails and is listed in Activity                                                                       |
| Field says `stage`                                        | `stage` only                                                                                                             |
| Tag says `pyck-route-stage`                               | `stage` only                                                                                                             |
| Field says `stage`, tag says `pyck-route-demo`            | Both `stage` and `demo`                                                                                                  |
| Order tagged `demo`, its customer labelled `stage`        | Both `demo` and `stage`                                                                                                  |
| Label names only a non-production connection              | That connection, as a copy. Nobody can ship the order                                                                    |
| Label matches nothing                                     | Nothing — the sync fails and is listed in Activity                                                                       |
| Label names a switched-off connection                     | Nothing — the sync fails and is listed in Activity                                                                       |
| Test order                                                | Everywhere it is routed, except production. Nobody can ship it. If that leaves nothing, the sync fails                   |
| Production is switched off                                | The other switched-on connections, as copies. Nobody can ship the order until it syncs again with production switched on |


# Running a test tenant before go-live

Trying pyck on your real orders without shipping anything, then switching to your live warehouse

Audience: Logistics Manager

You can connect a pyck test tenant to your live store and let it receive your real products, customers and orders, before the live warehouse takes over. Nothing is shipped, no stock moves, and customer details are replaced with made-up ones. When you are ready, one switch makes the live warehouse take over.

## What a test connection can and cannot do

|                                              | Production connection                | Every other connection     |
| -------------------------------------------- | ------------------------------------ | -------------------------- |
| Receives your products, customers and orders | Yes                                  | Yes                        |
| Customer details                             | Real                                 | Replaced with made-up ones |
| Receives orders placed in test mode          | Never                                | Yes                        |
| Can ship an order in Shopify                 | Yes, for orders that were sent to it | **Never**                  |
| Can change your Shopify stock                | Yes                                  | **Never**                  |

There is no separate setting for this. A connection that is not the production connection is a test connection, and it is limited this way whatever it is called.

In the copies a test connection receives, names, emails and phone numbers are made up, street lines are replaced and a second address line is dropped. City, postal code, province, country and company stay, so shipping logic still has a real destination. The same customer always gets the same made-up identity, so their orders stay linked to them. An order without a customer account gets a made-up identity of its own.

Notes, tags and metafields are copied as they are. Do not keep personal details in them if a test tenant should not see them.

## How to set it up

You end up with two connections: your production connection, switched off, and the test connection, switched on.

1. **Finish** [**setup**](/shopify-app/setup)**.** The first connection is always called `production`. Use the details of your live warehouse if you already have them; you can change the endpoint and token later, the name stays.
2. **Add the test connection.** Open **Warehouses** and choose **Add warehouse**. Either choose **Sign in to pyck** and pick the test tenant, or choose **Paste an API key** and enter the test tenant's endpoint and API key. When you paste, give it a label such as `testing` and leave the role on **Test copy**. A connection added by signing in is always a test copy, and its label is made from the tenant's name. The app registers itself with the test tenant when you save. Saving does not create the app's schemas there.
3. **Switch the test connection on.** A new connection starts switched off and receives nothing, and the message after saving says so. Open it from the **Warehouses** list, answer **Choose how this warehouse gets its schemas** with **Create the standard schemas** or **I'll map my own** (see [Setup](/shopify-app/setup#choose-how-the-warehouse-gets-its-schemas)), then choose **Switch on** under **Danger zone**.
4. **Keep production off.** Production also starts switched off after setup. If you have already switched it on, open `production` from the **Warehouses** list and, under **Danger zone**, choose **Switch off…** and confirm. Production now receives nothing and cannot call back.
5. **Check that products, customers and orders are switched on** under **Settings**, in the **Sync scope** card.

The Warehouses page now shows a warning that your production warehouse is switched off and that your other switched-on warehouses still receive anonymised copies. That is expected while you test. If no warehouse is switched on yet, the warning instead says that nothing is sent to pyck and nothing comes back.

Switched off only means production receives no store data. You can still prepare it while you test: edit its [data mapping](/shopify-app/data-mapping) and create or revoke its worker keys. A worker key of a switched-off warehouse cannot get Shopify access yet; the app refuses that until the warehouse is switched on.

From now on, every product, customer and order goes to the test tenant as a copy. No order is sent to production, so nothing can be marked as shipped in Shopify, and your stock counts are never written to.

Only orders created or changed after setup arrive on their own. To bring existing orders over, choose **Sync now** on the **Home** page.

{% hint style="warning" %}
**Do not set the test connection's role to Production.** It would start receiving your customers' real details and could ship real orders — including every order it already received as a copy, whether or not another warehouse is picking it. The app asks you to confirm and says so, but only you know which connection is which.
{% endhint %}

## Going live

1. Open `production` from the **Warehouses** list. If its page still asks **Choose how this warehouse gets its schemas**, answer that first: switching on waits for it (see [A warehouse cannot be switched on](/shopify-app/troubleshooting#a-warehouse-cannot-be-switched-on)). Then, under **Danger zone**, choose **Switch on and go live…**. The app shows what starts at once: real customer details, shipping and stock writes. Confirm.
2. **Switch the test connection off** on its own page, or leave it on to keep receiving copies. It cannot ship either way.
3. **Bring your data over.** Choose **Sync now** on the **Home** page. Switching production on does not send it anything on its own. Orders that were synced while production was off cannot be shipped by production yet. Each one can be once it syncs again with production switched on, because that sync sends it to production.

Decide with your team before step 3 what happens to orders that are still open. An order that is open on the day you go live may already be in your old fulfilment process, and syncing it makes pyck pick it too.

Switching production on is reversible, but shipments and stock changes it has already sent to Shopify are not undone.

## Things to watch

* **Deleting your last connection** reopens setup and stops all syncing.
* **Labels are permanent.** Tags and fields in your store point at them, so choose names like `testing` or `stage` deliberately.
* **Orders placed in test mode** never reach production, so they are never shipped. To test the shipping report itself, use a real order in a development store.
* **A worker key can bypass this.** If a pyck workflow gets its own Shopify access through a worker key, the key's permissions decide what it may do. Do not give a test tenant's key permissions to change fulfilments or stock.

See [Sending data to several pyck tenants](/shopify-app/routing) for how labels steer individual records, and [When something looks wrong](/shopify-app/troubleshooting) if a tenant is refused.


# Warehouse stock

Letting pyck drive the stock counts your Shopify locations show

Audience: Logistics Manager

pyck knows what is actually on the shelf. This feature copies that count into Shopify so your storefront sells what you really have.

It is off until you switch it on.

{% hint style="danger" %}
**pyck decides the stock count at every paired location.** Each sync writes pyck's number over whatever Shopify holds. Any on-hand quantity you edit by hand in the Shopify admin is overwritten at the next sync and the change is lost. Correct stock in pyck, not in Shopify.

In pull mode a hand edit survives less than one interval. In push mode it can be gone within seconds.
{% endhint %}

## 1. Pair each location with a storage area

Nothing happens until a Shopify location is paired with the pyck **storage area** that holds its stock.

Pairing lives on the **Stock sync** page, in the **Locations and storage areas** card: choose **Pair locations**. The storage areas always come from your production connection — no other tenant may write your stock. Without a production connection the card says "No production warehouse yet" and nothing can be paired.

The rules are strict, and the app will refuse a pairing that breaks them:

* **One storage area stocks one location.** An area cannot feed two locations. A location has one area: choosing a different area for it replaces the old pairing.
* **An area nested inside another cannot be paired alongside it.** A pyck area's count includes everything below it, so pairing both a parent and its child would count the same goods towards two Shopify locations. Areas sitting side by side are fine.
* A **virtual** storage area — one pyck uses to record movements rather than to hold goods on a shelf — can be paired, but the app warns you. What it counts is unlikely to match what is in the location.

**Pairings tie the production role to its connection.** A storage area belongs to one pyck tenant, so a pairing only makes sense for the connection it was made with. While any location is paired, the app refuses **Make production** on another connection and **Make test copy** on the current one, and says how many locations are paired. Nothing is changed. To move production to another tenant, first remove each pairing: on the **Stock sync** page, set the location to **Not paired** and choose **Remove pairing**. Then switch production, and pair the locations again with the new tenant's storage areas.

## 2. Choose how stock reaches Shopify

The **Stock sync** card on the same page offers three options. Pick one and choose **Save** — they cannot run together, because each would overwrite the other's work at unpredictable moments.

| Option                                         | What happens                                                                                                                                |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Off**                                        | Nothing reads pyck and nothing writes stock. Your Shopify quantities stay exactly as they are.                                              |
| **On — this app reads pyck every hour** (pull) | The app reads each paired storage area once an hour and writes the counts onto its Shopify location. Every run is checked before it writes. |
| **On — pyck reports each change** (push)       | Nothing runs on a timer. Your pyck workflow calls the app whenever stock moves and the app writes that one quantity straight to Shopify.    |

The preview approval and the safety limits described below apply to pull mode. Push mode writes one quantity at a time, so there is no whole warehouse being read at once to check. Push also does not use the pairings: the workflow names the Shopify location itself, and without one the app writes to the first location the product is stocked at.

The option you choose is enforced. While the mode is **Off** or pull, the app refuses every stock change your pyck workflow sends and tells it which mode is set, so a workflow left running cannot write stock behind your back or race the hourly pull. Reading a stock level still works in every mode.

## 3. Approve the first sync for each location

A location that has never synced will not be written to until you say so.

On the **Stock sync** page, choose **Check what pyck holds**. The app reads the whole paired storage area while you wait, reports how many products it found counts for, and writes nothing. A large warehouse can take a few minutes. When the numbers look right, choose **Approve first sync**.

The approved sync is queued and starts within a minute; you can close the page. An approved sync that has not started within an hour is dropped as "Never started", and you approve again. After the first sync succeeds, syncing carries on by itself.

The first sync of a large warehouse may also have to switch thousands of products on at that location in Shopify first, one request each. That work is spread across several later syncs, so stock arrives in batches until it is done.

## What actually gets written

These three rules are the heart of the feature.

| What pyck reports for a SKU            | What happens in Shopify                                                  |
| -------------------------------------- | ------------------------------------------------------------------------ |
| A number, **including 0**              | It is written. Zero is a real sell-out and has to reach your storefront. |
| **No entry at all**                    | The SKU is **skipped**. It is never set to zero and never touched.       |
| pyck errors, or cannot be reached      | The run writes **nothing at all**. Not partially, not zeroes.            |
| Shopify refuses some of the quantities | The rest are written. The next sync writes the whole count again.        |

The second rule is the important one. It means a pyck outage, an expired key, a pairing pointing at a deleted storage area or a mis-scoped tenant cannot empty your catalogue — all of them produce *absences*, and absences write nothing.

So anything you do not keep in the paired storage area is left exactly as it is in Shopify.

A SKU that more than one Shopify variant uses is also skipped rather than guessed at. The app will not decide for you which of two variants a count belongs to. The same goes for a variant that does not track inventory in Shopify.

## Why your available quantity can look wrong

The app writes Shopify's **on-hand** count — the physical number of units in the warehouse.

Shopify works out **available** itself, by subtracting the units already committed to open orders. So:

```
available = on-hand − committed to open orders
```

That is why a location can legitimately show a **negative available**: pyck says there are 3 units on the shelf, Shopify has 5 already promised to customers, so 2 are owed. That is accurate, not a bug — you are oversold and the number is telling you by how much.

It is also why the app writes on-hand rather than available. Writing a physical count into available would add the committed units back and let you sell them twice.

In push mode, a workflow can also send a change instead of a count ("3 fewer"). That change is applied to available, which moves on-hand by the same amount.

## A sync that stops is the safety net working

Every stopped run means the same thing: **nothing was written and your stock was left alone.** On the Stock sync page, stopped runs are shown in orange, not red, for exactly this reason. **Activity** lists them as failed.

A run stops when:

| Reason                                | What it means                                                                                                                                                                                                                                           |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Waiting for your approval             | The location has never synced. Approve it on the Stock sync page.                                                                                                                                                                                       |
| Would have emptied the location       | pyck reported more of this location's stock as zero than one sync may write: more than 50 products, and more than 5% of the products in stock there. Far more often a storage area that was emptied, re-seeded or renamed in pyck than a real sell-out. |
| The paired storage area is gone       | The area no longer exists in pyck. Pair the location with one that does.                                                                                                                                                                                |
| pyck reported far less than last time | This run found more than 30% less stock than the last successful one (and at least 50 products fewer). Usually a pyck-side problem rather than a real fall.                                                                                             |
| The run took too long                 | Its counts were already out of date by the time it was ready to write, and writing them would have moved your stock backwards.                                                                                                                          |
| The sync stopped part-way             | The app restarted mid-sync. Nothing partial was left behind; the next sync starts over.                                                                                                                                                                 |

Apart from the approval and a missing storage area, these clear themselves. Once pyck reports normal counts again, the next sync goes through without anyone doing anything.

A run can also end in red, as "Did not finish": the sync could not read pyck or write Shopify, or Shopify would not stock some products at that location (usually a location switched off in Shopify), or Shopify refused some quantities. Activity names the products and Shopify's reason.

### Overriding the emptying limit

When a run would set too much of a location to zero, it stops and offers **Let this sync through once…**. Use it only if the warehouse really is empty — every one of those products stops being sellable from that location the moment it is written. The app asks you to confirm how many SKUs it will set to zero.

The override applies to one sync. The next sync is checked in exactly the same way, so if pyck is still reporting the area as empty it stops again, which is what you want.

## Prerequisites checklist

For pull mode, stock will not move unless all of these are true:

* You have a **production connection**, and it is switched on.
* The Shopify location is **paired** with a pyck storage area.
* **On — this app reads pyck every hour** is chosen and saved.
* The location's **first sync has been approved**.

For push mode, you need a switched-on production connection — the stock has to come from it — and **On — pyck reports each change** chosen and saved. It needs no pairing.

If something looks wrong, see [When something looks wrong](/shopify-app/troubleshooting).


# When something looks wrong

Common symptoms in the Shopify app and what they mean

Audience: Logistics Manager

Symptoms you may meet, what each one means, and what to do about it.

Start at the **Activity** page. It lists every sync attempt with its status and details, and most of what follows is visible there. Select an entry to open its details: the **Record ID** links to the product, order or customer in your Shopify admin, so you can check the record the entry is about.

## A stock sync stopped because it would have emptied a location

**What you see.** A red banner on the **Stock sync** page: "Sync stopped — it would have emptied *your location*", naming how many SKUs would have gone to zero.

**What it means.** pyck reported far more of that location's stock as zero than one sync is allowed to write. **Nothing was written and your Shopify stock is exactly as it was.** Far more often this is a storage area that was emptied, re-seeded or renamed in pyck than a real sell-out, so the app stops instead of taking your storefront down.

**What to do.** Check the paired storage area in pyck. Once it reports normal counts again the next sync goes through by itself, with nothing to click.

If the warehouse really did empty, use **Let this sync through once…** and confirm. It applies to one sync only — the next is checked exactly as before.

## "No production connection"

**What you see.** A warning "No production warehouse yet" on the **Stock sync** page, or a `403` reported by your pyck worker when it tries to read or write stock.

**What it means.** Only the production connection may fulfil orders and write stock. Your store currently has none — usually because it was deleted, or because a different connection was made production and the old one demoted.

**What to do.** Open **Warehouses**, open the warehouse that runs your real stock and set its **Role** to **Production**. With only one connection, use **Use this warehouse for stock and fulfilment** in the banner on the Warehouses page instead. If the connection exists but is switched off, open it and choose **Switch on and go live…** under **Danger zone**: a switched-off production connection is refused for the same reason a missing one is.

## A warehouse cannot be switched on

**What you see.** On a switched-off warehouse's page, the **Switch on** (or **Switch on and go live…**) button under **Danger zone** is greyed out and reads "Choose how this warehouse gets its schemas first." The page starts with the card **Choose how this warehouse gets its schemas**, and its **Data mapping** section shows **Not chosen yet**. On the Home page, **Needs you** reads "*label* is switched off until you choose how it gets its schemas." with a **Choose** link to that warehouse.

**What it means.** Nobody has decided yet whether the app creates its standard Shopify schemas in this tenant or whether you map your own. Until that is answered, the warehouse cannot be switched on.

**What to do.** Answer the card: **Create the standard schemas**, or **I'll map my own** and then set up the [data mapping](/shopify-app/data-mapping). If the card shows an error instead, read it there: "Save an API key on this warehouse first — the schemas are created in pyck." means the warehouse has no API key yet; any other message means pyck could not create the schemas, and nothing was recorded, so you can choose again. See [Setup](/shopify-app/setup#choose-how-the-warehouse-gets-its-schemas).

## Changing the production role is refused

**What you see.** On a warehouse's page, after setting its **Role** to **Production** or **Test copy**, an error such as "Could not make stage production: 2 Shopify locations are paired with production's storage areas."

**What it means.** Shopify locations are paired with storage areas of your current production tenant. Those areas exist only in that tenant, so the production role cannot move while the pairings are in place. **Nothing was changed** — the current connection is still production.

**What to do.** On the **Stock sync** page, set each paired location to **Not paired** and choose **Remove pairing**. Then try again, and pair the locations with storage areas of the new production tenant. See [Warehouse stock](/shopify-app/stock#1-pair-each-location-with-a-storage-area).

## Switching a warehouse on is refused

**What you see.** On a warehouse's page, after choosing to switch it on, the error "Choose how this warehouse gets its schemas before switching it on: create the standard Shopify schemas, or map your own."

**What it means.** Before a warehouse can be switched on, you must decide how it gets its schemas. There are two choices:

* **The standard Shopify schemas.** The app creates `shopify_item_v1`, `shopify_customer_v1`, `shopify_order_v1`, `shopify_order_item_v1` and `shopify_file_v1` in the tenant. Schemas the tenant already has are left as they are.
* **Your own schemas.** The app creates nothing. You map your tenant's schemas under **Data mapping** on the warehouse's page. See [Designing pyck schemas for Shopify](/shopify-app/schema-design).

This warehouse has no choice on record yet, so it stays switched off. **Nothing was changed.** The rule applies to warehouses connected since the choice was introduced. Warehouses connected before then already have a mode, so they count as decided. Switching a warehouse off is never refused.

**What to do.** Make the choice for that warehouse, then switch it on again. You choose only once per warehouse, and a choice already on record is never changed, even if you submit it again or from a second tab.

* The standard schemas are created in pyck, so the warehouse needs a saved API key first. If you choose them before saving a key, the app asks you to save one.
* If the app cannot create the standard schemas, it records no choice and shows why. Fix the cause and choose again.
* If you pick your own schemas, map them before you switch the warehouse on.

## A record will not sync, and the reason names a label

**What you see.** In **Activity**, a failed entry saying an unknown pyck route label was used, or that the label names a connection that is switched off.

**What it means.** The product, customer or order carries a route label — in its pyck route field or a `pyck-route-…` tag — that matches no connection on your store. A typo like `pyck-route-stagg` does this, and so does a label pointing at a connection that has since been deleted or deactivated.

The record was **not** sent anywhere. It did not partially deliver and it did not fall back to sending everywhere, because you wrote a label in order to restrict it and quietly ignoring that would send your data to tenants you deliberately excluded.

The label can also come from the order's customer: their tags, or what their last sync recorded.

**What to do.** Compare the label against your connection names under **Warehouses**. Fix the label on the record or its customer, or reactivate the connection it names. The record syncs on its next change; to push it immediately, choose **Sync now** on the Home page.

See [Sending data to several pyck tenants](/shopify-app/routing) for how labels work.

## A value I set in pyck keeps changing back, or disappears

**What it means.** The field is inside `shopify`, or it has a Shopify source in the connection's **Data mapping** (on the warehouse's page under **Warehouses**). Either way Shopify owns it. Every sync writes Shopify's value again, and a value cleared in Shopify is removed in pyck. A mapping that still names a metafield definition deleted or renamed in Shopify counts as cleared too.

**What to do.** Change the value in Shopify. For a field of your own, you can instead set it to **Not synced** so pyck owns it from then on; `shopify` itself always follows Shopify. If the field keeps disappearing although Shopify has a value, look in the **Data mapping** for a source marked **Not defined in Shopify** and pick the current one. See [What a sync overwrites in pyck](/shopify-app/data-mapping).

## A record fails with "jsonschema validation failed"

**What you see.** In **Activity**, a failed entry such as `at '/unitOfMeasure': maxLength: got 6, want 3` or `at '/status': got array, want string`. When an existing product is updated because it changed in Shopify, the entry only appears after you choose **Record every attempt** on the Activity page; without it, the product simply stops changing in pyck. A required field that was cleared in Shopify fails the same way.

**What it means.** A mapped Shopify source sends a value your pyck schema does not accept, and pyck rejects the whole record. Typical causes: a product's **Weight unit** (`POUNDS`) mapped to a short unit-of-measure field, or **Order tags** (always a list) mapped to a single-value field. If the path starts with `/shopify/`, the pyck schema describes the contents of the `shopify` field with types or limits Shopify's values do not fit; that is for whoever maintains the schema, see [Designing pyck schemas for Shopify](/shopify-app/schema-design#your-schema-must-accept-the-shopify-field).

**What to do.** In **Data mapping** (on the warehouse's page under **Warehouses**), pick a source whose values fit the field, or set the field to **Not synced**. The record syncs on its next change, or straight away with **Sync now** on the Home page.

## A record fails with "Could not move … onto the latest version of its DataType"

**What you see.** In **Activity**, a failed entry such as "Could not move item SKU-1 onto the latest version of its DataType: its data does not fit that version, so nothing was written and the record stays as it is in pyck. Fix the fields named below in pyck; the next sync moves it." It ends with pyck's own message, for example `at '/lagerzone': missing property`. The same can name a customer, an order or an order line.

**What it means.** The schema the record uses in pyck has a newer version, and the app moves the record onto it together with its data in one write. pyck checks the data against the new version, and something in it does not fit: usually a field your team maintains in pyck that the new version requires or declares differently. **Nothing was written**: the record keeps its old data and its old version.

**What to do.** Fix the field pyck names on that record in pyck, for example fill in the missing `lagerzone`. The next sync of the record moves it onto the new version, or choose **Sync now** on the Home page. If many records fail the same way, ask whoever maintains the schema whether the new version should require that field.

## A record fails with "DataType … not found", or a warehouse shows "Needs setup"

**What you see.** In **Activity**, a failed entry ending in `DataType shopify_item_v1 not found` (or another `shopify_…` schema). Under **Warehouses**, the warehouse is badged **Needs setup**: "This warehouse is only part way through its setup. Check connection finishes it."

**What it means.** The tenant does not have the app's own schemas yet. Adding a warehouse, including your first one during setup, creates only `shopify_config_v1`, which holds the callback details pyck needs. The schemas for products, customers, orders, order lines and files are not created then, because whether a tenant gets them is your decision.

**What to do.** Open the warehouse under **Warehouses** and choose **Check connection**. It creates the missing schemas and checks the connection. It is only available while the warehouse is switched on. Then choose **Sync now** on the Home page to send the records that failed.

## A file attached in Shopify disappeared from pyck

**What it means.** Files always follow Shopify. When a file metafield is cleared or points at a different file, the file the app delivered earlier is deleted. Files your team attached in pyck directly are not affected.

**What to do.** Attach the file again in Shopify. See [What a sync overwrites in pyck](/shopify-app/data-mapping#files).

## "Shopify metafields are not synced" on Home

**What you see.** In **Needs you** on the Home page: "2 Shopify metafields are not synced — production does not receive their values", with when this was checked and a **Review metafields** link.

**What it means.** Your store defines metafields that the production warehouse's schemas do not carry, so their values never reach pyck. This shows only once the catalogue has been sent. Fields of entities that use a custom mapping are not counted: there a metafield reaches pyck only through the mapping. The count is not checked live on every visit. The app checks again in the background when you open Home and the last check is over an hour old, so a metafield created or deleted in Shopify can take up to an hour to show here. File metafields are uploaded anyway and are never counted.

**What to do.** Choose **Review metafields**. It opens the warehouse's **Data mapping**, where the **Shopify metafields** block lists each field. **Add** the ones pyck should carry, or **Add all**. For a field pyck should not receive, choose **Keep out**: it is no longer counted, and the hint goes away once every listed field is added or kept out. A field added now gets its values when the record next changes, or straight away with **Sync now**. See [Connections in Auto mode](/shopify-app/data-mapping#connections-in-auto-mode).

If **Check** says it could not read your Shopify metafield definitions, Shopify did not answer in full, often because of a rate limit. Nothing was stored. Try again in a moment.

## A product is not appearing in pyck

**What you see.** The product exists in Shopify but never turns up in pyck. For a new product, Activity shows a failed entry saying variants without SKU were not synced. A **Sync now** run counts them as "Skipped (no SKU)". When an existing product changes, nothing is shown unless **Record every attempt** is on.

**What it means.** The most common cause is that **the variant has no SKU**. pyck identifies stock by SKU, so a variant without one has nothing to be matched against and is never sent. This is not a setting you can loosen.

**What to do.** Give the variant a SKU in Shopify and it will sync on the next change. If some variants of a product have SKUs and some do not, only the ones with SKUs are sent.

Two other possibilities worth checking:

* **Products are switched off** under **Settings**, in the **Sync scope** card. Activity then shows "Product sync disabled", under the **All** filter.
* The product carries a route label — see the previous section.
* The product was deleted before the app could read it. Activity shows it as skipped with "No longer exists in Shopify".

## Stock is not updating in Shopify

Work down this list; the first one that is not true is your answer.

| Check                                                 | Where                                                                     |
| ----------------------------------------------------- | ------------------------------------------------------------------------- |
| The location is **paired** with a pyck storage area   | **Stock sync** page, **Locations and storage areas** card                 |
| The mode is **not off**                               | **Stock sync** page                                                       |
| The location's **first sync has been approved**       | **Stock sync** page — a location badged "Never synced" is waiting for you |
| A **production connection** exists and is switched on | **Warehouses**                                                            |

In push mode, the location pairing and the approval do not apply. If your pyck worker reports a `403` saying stock sync is set to `"off"` or `"pull"`, not `"push"`, the change was refused because **On — pyck reports each change** is not chosen and saved on the **Stock sync** page. Nothing was written. Choose it and save, or leave the mode as it is and stop the workflow from sending stock changes.

If all four are fine, look at the location's last run on the Stock sync page. A run badged in orange stopped on purpose and wrote nothing — see the table on the [Warehouse stock](/shopify-app/stock) page for what each reason means. In **Activity**, the same run is listed as failed.

## One SKU never changes while others do

**What it means.** Two likely causes, both of which the app handles by leaving the SKU alone rather than guessing:

* **pyck holds no entry for that SKU.** It is skipped, never set to zero. Anything you do not keep in the paired storage area stays exactly as it is in Shopify.
* **More than one Shopify variant uses that SKU.** The app refuses to decide which of them a count belongs to.

Less often, the variant does not track inventory in Shopify, or the product has not been switched on at that location yet — the first syncs of a large warehouse do that in batches.

**What to do.** For the first, check the item exists in the paired storage area in pyck. SKUs must match exactly, including upper and lower case. For the second, give the variants distinct SKUs in Shopify. For the third, turn on inventory tracking for the variant in Shopify.

## A product shows as available below zero

**What it means.** This is usually correct, not a fault. pyck reports the physical count on the shelf, and Shopify subtracts the units already promised to open orders:

```
available = on-hand − committed to open orders
```

3 on the shelf with 5 already sold shows as −2 available. You are oversold, and the number is telling you by how much.

**What to do.** Treat it as a stock alert rather than a display bug.

## An order was not shipped, and pyck refuses it

**What you see.** Your pyck worker gets a `403` or a `409` when it reports an order as shipped.

**403 — "not the production connection".** The tenant that called is not your production connection. Only production may ship orders or change stock, so a test, stage or demo tenant is always refused, whatever order it asks about. This is by design and cannot be switched off. If this tenant should be shipping your real orders, it has to become the production connection first. See [Running a test tenant before go-live](/shopify-app/test-tenant).

**403 — "deactivated".** The tenant that called is switched off. Open it under **Warehouses** and switch it back on under **Danger zone**.

A test or copy tenant always gets one of these two `403`s. The `409` below only reaches your production connection.

**409 — "never delivered to connection".** Production may only ship an order that its last sync sent to production. This order was not: it was last synced while production was switched off, or before this connection was added, or the app has never synced it. A test order is never sent to production, so it always gets this answer. Production can ship the order once it syncs again with production switched on: change the order, or choose **Sync now** on the Home page.

**What to do.** Nothing on a copy's side — it should log and move on. On production's side, make the order sync again as described above.

## A test order reached the wrong place, or did not reach production

Orders Shopify marks as tests — Bogus gateway or Shopify Payments test mode — are deliberately excluded from the production connection whatever labels they carry. They still reach your other tenants, and nobody can ship them. This is by design and cannot be overridden. To test the shipping report itself, use a real order against a development store.

If production is the only connection a test order would reach, it reaches none, and Activity shows "Every routed connection was excluded by the test-order rule."

## Nothing at all is syncing

* Setup may be incomplete. If the app's menu shows **Setup** instead of Warehouses, Stock sync, Activity and Settings, no connection exists. See [Setup](/shopify-app/setup).
* Deleting your last connection reopens setup and stops syncing until you connect one again.
* Products, customers and orders each have their own switch under **Settings**, in the **Sync scope** card.
* A newly added warehouse starts switched off, whether it was added during setup, with **Add warehouse** or by signing in to pyck. Open it under **Warehouses**, answer **Choose how this warehouse gets its schemas**, then switch it on under **Danger zone**. See [Switch the warehouse on](/shopify-app/setup#switch-the-warehouse-on).
* Every warehouse may be switched off under **Warehouses**. Each product, customer or order change is then skipped, not failed: Activity shows it as skipped with "No warehouse is switched on", and a **Sync now** run ends as skipped without listing any items. Nothing is read from Shopify or sent to pyck, and Shopify does not retry the change. Once you switch a warehouse back on, choose **Sync now** on the Home page to send what changed in the meantime.
* Skipped syncs only appear in Activity under the **All** filter.
* Use **Check connection** on the warehouse's page under **Warehouses** to check the connection itself is healthy. It is only available while the warehouse is switched on.


# Glossary

Essential warehouse and logistics terminology for developers

Audience: Programmer

This primer introduces developers to common warehouse and logistics terminology. Whether you're building integrations, designing systems, or just trying to understand the domain, these definitions will help you navigate the world of supply chain and warehouse management.

## Inventory Management

### ABC Analysis

A method of categorizing inventory items based on their importance and value. "A" items (typically 20% of items) account for 80% of the value, "B" items are moderately important, and "C" items are least valuable but often most numerous. This helps prioritize warehouse space, cycle counting frequency, and management attention.

### Safety Stock

Extra inventory kept on hand to prevent stockouts caused by variability in demand or supply delays. Think of it as a buffer - like keeping extra batteries at home in case of emergency. The amount is calculated based on lead times, demand variability, and desired service levels.

### Reorder Point

The inventory level that triggers a new purchase order. When stock drops to this point, it's time to reorder to avoid running out before the next delivery arrives. It's calculated as: (average daily usage × lead time) + safety stock.

### Min/Max Levels

Inventory control limits where "min" is the lowest acceptable stock level (triggers reordering) and "max" is the maximum to stock (prevents over-ordering). It's like setting low-fuel and full-tank indicators for inventory - simple but effective for many products.

### Dead Stock

Inventory that hasn't sold or moved for an extended period (often 12+ months). It ties up capital and warehouse space, like having a closet full of clothes you never wear. Companies often liquidate dead stock at a loss to free up resources.

### Consignment Stock

Inventory owned by the supplier but stored at the customer's location. The customer only pays when they actually use or sell the items. It's like a vending machine model - the supplier maintains ownership until consumption.

### Kitting

The process of grouping individual items together to create a new SKU that's sold as a single unit. For example, bundling a camera, memory card, and case into a "photographer's starter kit." This can be done in advance or on-demand during order fulfillment.

### Bill of Materials (BOM)

A hierarchical list of all components, parts, and materials needed to manufacture or assemble a product. Think of it as a recipe that specifies every ingredient and quantity needed. Essential for manufacturing, kitting, and understanding product costs.

### Advanced Planning and Scheduling (APS)

Software used to align production plans and warehouse operations for optimal efficiency. It coordinates manufacturing schedules with warehouse capacity, labor availability, and shipping requirements to optimize the entire supply chain.

## Location & Storage Concepts

### Slotting Optimization

The strategic placement of products within a warehouse to minimize travel time and maximize efficiency. Fast-moving items go in easily accessible locations, heavy items on lower shelves, and complementary items near each other. It's like organizing your kitchen for cooking efficiency.

### Cubic Capacity

The three-dimensional space (length × width × height) available for storage. Unlike floor space, cubic capacity considers vertical space utilization. Modern warehouses maximize this by using tall racking systems and equipment that can reach high shelves.

### Pick Face

The primary location where workers pick items for orders, usually at ground level or easy-to-reach heights. It's like the front row of products in a grocery store shelf. When pick face inventory runs low, it's replenished from bulk storage locations.

### Reserve/Bulk Storage

Overflow inventory locations used to replenish pick faces. These are often in less accessible areas like high racks or deep storage. Think of it as the stockroom behind a retail store that customers don't see.

### Staging Area

A designated space where completed orders are placed before shipping or where received goods wait before putaway. It's like a temporary holding zone - similar to a restaurant's pass where completed dishes wait for servers.

### Marshalling Area

A space where goods are organized and sequenced for specific purposes, like loading trucks in delivery route order. Think of it as a pre-departure organization zone where everything gets arranged for optimal execution.

## Order Processing

### Order Consolidation

Combining multiple orders going to the same destination or customer into a single shipment. This reduces shipping costs and handling, like carpooling for packages. It may require holding some orders until others are ready.

### Consolidation

Combining shipments or SKUs to optimize space and reduce transport costs. This broader concept includes consolidating products from multiple suppliers into single shipments or combining different SKUs into mixed pallets for more efficient transportation.

### Partial Shipment

Sending available items from an order immediately while backordered items ship later. Customers get what's in stock quickly rather than waiting for everything. It increases shipping costs but improves customer satisfaction.

### Backorder

An order for items that are temporarily out of stock. The order is accepted and fulfilled when inventory becomes available. It's like a reservation system for products - you're in line when stock arrives.

### Pre-allocation

Reserving inventory for specific orders before actual picking begins. Also called "soft allocation" because the physical inventory hasn't moved yet. This prevents the same items from being promised to multiple orders.

### Order Cutoff Time

The deadline for orders to be processed the same day. Orders placed after cutoff are processed the next business day. It's like a postal service's last collection time - miss it and your mail goes tomorrow.

### Priority Orders

Orders that jump the queue due to service level agreements, expedited shipping, or customer importance. These might include emergency medical supplies or paid rush deliveries. They're like the express lane at a grocery store.

### Wave Picking

Grouping multiple orders into waves to optimize picking routes. Orders are released to the warehouse floor in batches (waves) based on factors like shipping schedules, zones, or carrier requirements. This improves efficiency by allowing pickers to work on similar orders together.

### Zone Picking

Assigning pickers to specific warehouse zones where they only pick items from their designated area. Orders requiring items from multiple zones are passed between pickers or consolidated later. This reduces travel time and allows workers to become experts in their zones.

## Warehouse Operations

### Goods-in/Goods-out

The receiving (goods-in) and shipping (goods-out) processes at warehouse dock doors. Goods-in involves unloading, checking, and recording incoming shipments. Goods-out handles loading and documenting outbound shipments. These are the main entry and exit points for all inventory.

### ASN (Advanced Shipping Notice)

An electronic notification sent by suppliers before shipment arrival, detailing what's coming, when, and how it's packed. It's like a heads-up message that helps warehouses prepare for incoming deliveries. ASNs enable better dock scheduling and labor planning.

### Dock Scheduling

Managing the timing and assignment of trucks to specific dock doors for loading/unloading. It prevents congestion and ensures resources (doors, staff, equipment) are available. Think of it as appointment scheduling for deliveries.

### Detention

Charges for delays in loading/unloading at docks. When trucks are held at the dock beyond the agreed free time (usually 2 hours), carriers charge detention fees. These costs motivate efficient dock operations and scheduling.

### Load Planning

Optimizing how items are arranged in trucks or containers for transport. Good load planning considers weight distribution, delivery sequence, and space utilization. It's like playing Tetris with boxes while considering physics and delivery routes.

### Returns/RMA

The process of accepting products back from customers. RMA (Return Merchandise Authorization) is the approval and tracking number for returns. Returns require inspection, restocking, repair, or disposal decisions - it's the reverse of the fulfillment process.

### Reverse Logistics

The entire flow of products moving backward through the supply chain - returns, repairs, recycling, and disposal. It's increasingly important for customer satisfaction and environmental responsibility. Unlike forward logistics, each item might take a different path.

### Quality Control Hold

Temporarily isolating inventory that needs inspection or has potential issues. Items in QC hold can't be shipped until cleared. It's like a quarantine system ensuring only good products reach customers.

### Inbound Logistics

The complete process of managing incoming shipments, from carrier scheduling through receiving and putaway. It encompasses transportation planning, dock management, receiving, quality checks, and getting products ready for storage or immediate use.

### Outbound Logistics

The flow of goods leaving the warehouse, from order allocation through shipping. This includes picking, packing, staging, loading, and carrier coordination. Outbound logistics ensures orders are fulfilled accurately and delivered on time.

### Packing List

A detailed document listing all items in a shipment, including quantities, descriptions, and sometimes weights or dimensions. It serves as a reference for receivers to verify shipment contents and is often required for customs clearance.

## Performance Metrics

### SLA (Service Level Agreement)

A contract defining specific performance standards like order accuracy, shipping time, or inventory availability. For warehouses, common SLAs include "99% of orders shipped same day" or "99.5% inventory accuracy." These drive operational priorities and penalties.

### KPI (Key Performance Indicators)

Measurable values that demonstrate operational effectiveness. Common warehouse KPIs include orders per hour, cost per order, and space utilization. They're like a dashboard showing if operations are healthy and improving.

### Order Fill Rate

The percentage of orders shipped complete on the first shipment. If 95 orders out of 100 ship complete, that's a 95% fill rate. High fill rates indicate good inventory management and availability.

### Perfect Order Rate

The percentage of orders delivered complete, on-time, damage-free, and with correct documentation. It's a comprehensive quality metric - much harder to achieve than simple fill rate. Even 95% perfect order rate means 1 in 20 customers has an issue.

### Inventory Turnover

How many times inventory is sold and replaced in a period (usually annually). Higher turnover means products move quickly, reducing holding costs. A turnover of 12 means you're selling your entire inventory monthly.

### Dwell Time

How long inventory sits in the warehouse between arrival and departure. Lower dwell time means faster flow and fresher products but requires precise coordination. It's especially critical for perishables or fashion items.

### Velocity

The speed of item movement through the warehouse system. High-velocity items move quickly from receiving to shipping, while low-velocity items stay longer. Understanding velocity helps optimize storage locations and picking strategies.

### On-Time In-Full (OTIF)

A comprehensive metric showing the percentage of orders delivered on time and complete. OTIF combines two critical factors - punctuality and accuracy. An order must meet both criteria to count as successful, making it a demanding but valuable performance indicator.

### Throughput

The amount of inventory moving through a warehouse in a given time period. Can be measured in units, pallets, or orders per hour/day. It indicates processing capacity and efficiency - like measuring a highway's traffic flow.

## Equipment & Warehouse Systems

### WCS (Warehouse Control System)

Software that directs real-time activities within warehouses, particularly automated equipment. While a WMS decides what needs to happen, the WCS controls how equipment executes those decisions. It's like the nervous system coordinating muscle movements.

### WMS (Warehouse Management System)

A software solution that manages and optimizes daily warehouse operations from receiving to shipping. It tracks inventory, directs workers, manages orders, and provides visibility into all warehouse activities. The WMS is the central brain of modern warehouse operations.

### Pick-to-Light

A system using LED displays at storage locations to guide order picking. Lights indicate which items to pick and quantity needed. Workers confirm picks with a button press. It's faster than paper lists and reduces errors through visual guidance.

### Voice Picking

Workers wear headsets and receive verbal instructions on what to pick. They confirm actions by speaking back to the system. It keeps hands and eyes free for picking while providing real-time guidance and confirmation.

### AGV/AMR

Automated Guided Vehicles follow fixed paths (like magnetic tape), while Autonomous Mobile Robots navigate dynamically using sensors and AI. Both transport goods without human drivers. Think of AGVs as trains on invisible tracks, AMRs as self-driving cars.

### Sortation System

Automated equipment that routes items to correct destinations based on barcodes or RFID. Common types include tilt-tray, cross-belt, and sliding shoe sorters. It's like a smart postal sorting facility that reads addresses and diverts packages automatically.

### Conveyor System

Motorized belts or rollers that transport items through the warehouse. They connect different areas and equipment, reducing manual carrying. Modern conveyors can merge, divert, and accumulate products as needed.

## Enterprise Integration Systems

### ERP (Enterprise Resource Planning)

The central business system managing finance, purchasing, sales, and inventory across the entire company. Popular systems include SAP, Oracle, and Microsoft Dynamics. The WMS typically syncs with ERP for order information and inventory updates.

### TMS (Transportation Management System)

Software that plans and optimizes shipment routing, carrier selection, and freight costs. It handles everything from parcel shipping to full truckloads. TMS connects with WMS to coordinate when shipments are ready and track deliveries.

### OMS (Order Management System)

Centralizes orders from all sales channels (web, stores, phone) and orchestrates fulfillment across multiple warehouses. It decides which warehouse ships each order based on inventory, location, and costs. Think of it as air traffic control for orders.

### MES (Manufacturing Execution System)

Controls and monitors production on the factory floor. For warehouses handling assembly or light manufacturing, MES manages work orders, quality checks, and production tracking. It bridges the gap between ERP planning and actual production.

### EDI (Electronic Data Interchange)

Standardized electronic communication between companies' computer systems. Common EDI documents include purchase orders (850), invoices (810), and shipping notices (856). It's like email for computers - structured data exchange without human intervention.

### API Gateway

A server that acts as a single entry point for all client API calls. It handles authentication, rate limiting, and routing to appropriate backend services. For warehouses, it manages connections between WMS and external systems like e-commerce platforms.

## Automation Control Systems

### AutoStore Controller

The brain of AutoStore systems - dense cube storage where robots retrieve bins. The controller optimizes robot paths, manages bin locations, and coordinates with the WMS. It's like a chess master moving pieces for maximum efficiency.

### Shuttle System Controller

Manages automated storage systems where shuttles move within racking to store/retrieve items. Common in goods-to-person systems where shuttles bring inventory to pickers. The controller tracks shuttle positions and optimizes task assignment.

### AS/RS Control

Automated Storage and Retrieval Systems use cranes or robots to handle pallets or cases in high-density storage. The control system manages equipment movement, inventory locations, and interfaces with WMS for task execution. It's like a giant vending machine for pallets.

### Carousel Control

Manages rotating storage systems that bring items to operators (horizontal or vertical carousels). The controller optimizes rotation sequences to minimize wait time when picking multiple items. Think of it as a motorized lazy Susan for inventory.

### Sorter Control System

Directs high-speed sortation equipment that can handle thousands of items per hour. It reads barcodes, makes routing decisions in milliseconds, and tracks items through the system. Different sorter types (tilt-tray, cross-belt) require specialized control logic.

### Print & Apply Systems

Automatically prints labels and applies them to moving products. The system must coordinate printing speed with conveyor movement and verify correct application. It's essential for shipping labels and compliance labeling.

## Integration & Middleware

### Message Queue Systems

Software that enables asynchronous communication between systems using messages. RabbitMQ and Apache Kafka are popular choices. They ensure messages aren't lost if a system is temporarily down and help manage traffic spikes.

### ESB (Enterprise Service Bus)

Middleware that connects different applications using standard protocols and data transformation. It's like a universal translator enabling systems with different languages to communicate. ESBs handle routing, transformation, and orchestration.

### Webhook Systems

Event-driven HTTP callbacks that notify systems when something happens. For example, when an order ships, a webhook might update the e-commerce platform. They enable real-time integration without constant polling.

### Real-time Event Streaming

Continuous flow of data about events as they happen. Apache Kafka is commonly used for streaming warehouse events like inventory movements, order updates, or equipment status. It enables real-time analytics and immediate response to changes.

## Yard & Fleet Management

### YMS (Yard Management System)

Software managing truck movements and trailer parking in warehouse yards. It tracks which trailers are where, what's in them, and when they need to move. Good YMS reduces driver wait times and improves dock utilization.

### Dock Management System

Schedules and tracks all dock door activities. It manages appointments, check-in/out, door assignments, and performance metrics. Integration with WMS ensures the right resources are ready when trucks arrive.

### Vehicle Tracking/Telematics

GPS and sensor systems that monitor vehicle location, speed, idle time, and maintenance needs. For delivery fleets, this enables route optimization and accurate delivery ETAs. It's like Find My iPhone for commercial vehicles.

### Warehouse Network

The collective group of warehouse locations managed as an integrated system. This might include distribution centers, fulfillment centers, and satellite locations all coordinated through shared systems and processes. Modern WMS solutions enable network-wide visibility and optimization.

### Intermodal Transportation

Using multiple transport modes (truck, rail, ship, air) in a single journey. Containers or trailers move between different carriers without unpacking. The WMS coordinates with various transport systems to track shipments across the entire intermodal journey.

### Less-Than-Truckload (LTL)

Shipping method for freight that doesn't require a full truck. Multiple shippers share truck space and costs. LTL shipments require careful planning for consolidation, routing, and dock scheduling to manage the complexity of partial loads.

### Landed Costs

The total cost of goods including purchase price, transportation, customs, duties, taxes, insurance, currency conversion, handling, and payment fees. Understanding true landed costs is essential for accurate pricing and profitability analysis.

### Handling Costs

Expenses related to physically moving and managing goods within a warehouse. This includes labor, equipment operation, packaging materials, and overhead. Tracking handling costs per unit helps identify efficiency opportunities.

### Network Analysis

Analyzing the warehouse layout, flow patterns, and throughput to identify bottlenecks and optimization opportunities. This strategic analysis considers travel distances, congestion points, and resource utilization to improve overall efficiency.

Understanding these terms will help you design better integrations, have meaningful conversations with logistics professionals, and build systems that truly serve warehouse operational needs.


# FAQ for Logistics Managers

Frequently asked questions about Pyck for logistics managers

Audience: Logistics Manager

## Does Pyck cover the entire fulfillment process?

Yes. Pyck provides data services for core fulfillment processes including **receiving** (inbound), **inventory management**, and **picking** (outbound). On top of these data services, the workflow system (powered by [Temporal.io](https://temporal.io)) can implement any fulfillment process — shipping, returns, bundling, and more.

The key principle: as long as the underlying data service exists, workflows can orchestrate any process you need. If your fulfillment requirements go beyond the currently available data services, our team will support you in adding them.

## Can existing WMS processes be gradually replaced?

Yes. Pyck supports a step-by-step migration approach as long as your existing system provides an API for data exchange. This allows both systems to coexist during the transition period, with data flowing between them until the full migration is complete.

## How can data structures be extended?

Every entity in Pyck has a JSON `data` field that is validated against a [DataType](/graphql-api/types/datatype) — a JSON Schema you define. This lets you add arbitrary structured fields to customers, items, suppliers, orders, and more without changing the underlying database schema.

For example, you could define a DataType for items that includes fields like `color`, `size`, `brand`, and `hazmat_class` — all validated automatically by the API.

## Is there a test instance or sandbox?

Customers can create as many tenants as needed within Pyck. These tenants can serve as separate environments — for example, development, staging, and production — or any other separation your workflow requires. Each tenant is fully isolated, so testing in a dev tenant has no impact on production data.


# FAQ for Developers

Frequently asked questions about Pyck for developers

Audience: Programmer

## How is data stored in Pyck?

Pyck uses a **multi-tenant architecture** with strict tenant isolation at the database level. Each tenant operates in a fully separated data space with no cross tenant data access. Within a tenant, multiple root level repositories (warehouses) can exist.

**PostgreSQL** serves as the primary data store. **S3-compatible storage** is used for files and attachments. The movement-based data model also enables **time-travel queries**, allowing you to query inventory state at any historical point in time.

## Which database is used?

**PostgreSQL** is the primary database. **S3-compatible storage** is used as object storage for files and attachments.

## What is the technology stack?

| Component        | Technology                      |
| ---------------- | ------------------------------- |
| API              | **GraphQL** with Federation     |
| Database         | **PostgreSQL**                  |
| Event Streaming  | **NATS.io**                     |
| Workflow Engine  | **Temporal.io**                 |
| Authentication   | **OIDC/OAuth2** (e.g., Zitadel) |
| Containerization | **Docker**                      |
| Orchestration    | **Kubernetes**                  |

The logical foundation is built on these core concepts:

* **Repositories** — hierarchical containers for anything that can hold goods
* **Movements** — every inventory change as an executable instruction with full audit trail
* **Movement Collections** — ordered sequences of movements with forward-looking stock validation
* **DataTypes** — JSON Schema-based validation for flexible custom data

## What are the Pyck framework building blocks?

The Pyck framework consists of three main components: the **Core** (backend services), the **Web App**, and the **Mobile App**.

**Core:** Backend services consisting of a **GraphQL API** (with Federation), **event streaming** (NATS.io), and **workflow orchestration** (Temporal.io).

**Web App:** Browser-based interface for managing warehouse operations, configuration, and monitoring.

**Mobile App:** Native mobile application for on-the-floor warehouse tasks such as picking, receiving, and inventory management.

## Do data types need to be defined from scratch?

No. Pyck comes with predefined Entities (e.g., items, orders, customers, suppliers) that cover common warehouse concepts out of the box.

**DataTypes** are specializations of these Entities —— you define them yourself using an editor to add custom fields tailored to your business needs. Every Entity has a data field that is automatically validated against the custom JSON schema you can define, so your custom data is structured and type-safe without any backend code or database changes.

## How are processes defined and modeled?

Pyck uses Temporal.io as its workflow engine. Logistics processes are defined as Temporal workflows — primarily in Go, as this is the Pyck SDK that is currently available, though Temporal itself supports multiple languages. The Pyck Go SDK is optional and serves as a convenience layer; workflows can also be implemented without it.

For Pyck-specific workflow concepts, see:

* [Workflows (Concepts)](/basics/workflows)
* [Workflows (Development)](/development/workflows)

For details on authoring Temporal workflows, refer to the [Temporal Go SDK documentation](https://docs.temporal.io/develop/go).

## What programming language is the code written in?

**Go.** All backend services are written in Go.

Maintainability is supported by:

* **API-first design** — the GraphQL schema drives implementation
* **Microservice architecture** — clear separation of concerns

## How do concurrent processes affect each other?

Pyck is designed to handle concurrent API requests without conflicts. Database transactions and stock validations ensure operational consistency, even under concurrent load.


# FAQ for System Administrators

Frequently asked questions about Pyck for system administrators

Audience: System Administrator

## Does Pyck run on-premise or in the cloud?

pyck is offered as a **managed SaaS** at `https://api.pyck.ai`, and this is the deployment we recommend.

The open-source core is licensed under the **Functional Source License** (FSL-1.1-ALv2), so you can host it yourself on Kubernetes (Docker Compose is meant for local development). A self-hosted installation is operated by you, not by pyck; we do not recommend on-premise operation.

## Where is customer data stored?

Customer data is hosted on **Hetzner** servers in **Germany**.

## What happens with data when AI features are used?

Pyck uses AI to **generate code from BPMN process definitions** — not to process customer data. No live warehouse data, order data, or personal data is sent to AI providers.

Additionally, Pyck exclusively uses AI providers that offer **Zero Data Retention (ZDR)** endpoints, meaning prompts and completions are not stored or used for training by the provider. For details on the retention policy, see [OpenRouter's ZDR documentation](https://openrouter.ai/docs/guides/features/zdr#openrouters-retention-policy).

## Is there integrated user authentication?

Yes. Pyck uses **Zitadel** as its identity provider for user authentication.

## How does authentication work?

Two authentication methods are supported:

1. **JWT Token Authentication** — tokens are obtained via the Zitadel auth flow (redirect to Zitadel login page, callback with token). Tokens expire and must be renewed via the refresh token flow.
2. **Personal Access Token (PAT)** — long-lived tokens for system integrations and automation, created through the Pyck administration interface.

Both are sent as Bearer tokens in the `Authorization` header:

```
Authorization: Bearer <token>
```

For full details, see the [Authentication](/development/authentication) documentation.

## What environment variables are required for deployment?

All pyck binaries require the following environment variable to be set:

* **`PYCK_ENV`** (required): Specifies the environment name (e.g., `production`, `staging`, `dev`)
  * This variable **must be set explicitly** in your deployment configuration
  * The application will fail to start if this variable is missing or empty
  * Used for namespace construction (e.g., `pyck-{PYCK_ENV}-workers`)

Example configuration:

**Docker Compose:**

```yaml
environment:
  - PYCK_ENV=production
```

**Kubernetes ConfigMap:**

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: pyck-config
data:
  PYCK_ENV: "production"
```

**IMPORTANT**: As of commit `15ffdc33`, `PYCK_ENV` has no default value. Deployments that previously relied on the implicit "local" default must now explicitly set this variable.

### Optional Health Check Configuration

Temporal workers expose a `/health` HTTP endpoint (enabled by default on port 8080) to support deployment health monitoring. This endpoint verifies that the worker is actively polling Temporal task queues.

The health server can be configured via these optional environment variables:

* **`HEALTH_DISABLED`**: Set to `1` to disable the health endpoint
* **`HEALTH_PORT`**: HTTP port for health checks (default: `8080`)
* **`HEALTH_INTERVAL`**: How often to probe Temporal (default: `10s`)
* **`HEALTH_TIMEOUT`**: RPC timeout for each probe (default: `3s`)
* **`HEALTH_MAX_STALE`**: Maximum age of last successful probe before reporting unhealthy (default: `90s`)

**Example Configuration:**

```yaml
environment:
  - HEALTH_PORT=9090
  - HEALTH_INTERVAL=30s
  - HEALTH_MAX_STALE=120s
```

The health endpoint returns:

* **200 OK** when the worker is actively polling Temporal
* **503 Service Unavailable** when polling has stalled or Temporal is unreachable

This is particularly useful for container orchestrators (Kubernetes, fly.io) that need to detect and restart wedged workers.

## Why use Pyck instead of extending an existing cloud WMS?

Pyck offers a **future-proof, reliable platform with no vendor lock-in**. The open architecture, based on industry-standard technologies (Go, PostgreSQL, Kubernetes, GraphQL, Temporal), ensures you are not dependent on a single vendor's proprietary platform. You retain full control over your data, deployment model, and technology stack.


# Introduction

GraphQL API Reference

This directory contains comprehensive documentation for the Pyck GraphQL API. The documentation is organized by category to help you quickly find what you need.

## Structure

* [**Queries**](/graphql-api/queries): Operations for fetching data from the API
* [**Mutations**](/graphql-api/mutations): Operations for creating, updating, or deleting data
* [**Types**](/graphql-api/types): Object types and interfaces used in the API
* [**Enums**](/graphql-api/enums): Enumeration types that define restricted sets of values
* [**Scalars**](https://github.com/pyck-ai/docs/blob/main/graphql/scalars/README.md): Custom scalar types used in the API

## Core Concepts

### Pagination

Many queries return paginated results using the Relay connection specification. These queries typically accept `first`, `after`, `last`, and `before` arguments for pagination control, and return connection objects that include:

* `edges`: A list of edges, each containing a `node` (the actual object) and a `cursor`
* `pageInfo`: Information to aid in pagination, including `hasNextPage`, `hasPreviousPage`, `startCursor`, and `endCursor`
* `totalCount`: The total number of items in the connection

### Filtering

Most queries accept a `where` argument that allows filtering results by various criteria. The filtering options vary by object type but typically include equality comparisons, range comparisons, string operations, and more.

### Ordering

Most queries accept an `orderBy` argument that specifies the field and direction to sort results by.

### Data Types

The API extensively uses a flexible data model where many entities have a `data` field of type `Map` that can store arbitrary JSON data. This allows for entity customization without schema changes.

## Common Operations

* Fetching entities by ID: Use the appropriate node query (e.g., `nodeAttachments`, `nodeInventory`)
* Listing entities: Use the plural query name (e.g., `attachments`, `inventoryItems`)
* Creating entities: Use the appropriate creation mutation (e.g., `createAttachment`, `createInventoryItem`)
* Updating entities: Use the appropriate update mutation (e.g., `updateAttachment`, `updateInventoryItem`)
* Deleting entities: Use the appropriate delete mutation (e.g., `deleteAttachment`, `deleteInventoryItem`)


# Getting Started

Getting Started with the GraphQL API

## Introduction

This guide will help you get started with the pyck GraphQL API. You'll learn how to make your first query, understand the response format, and begin exploring the capabilities of the API.

## Prerequisites

Before you begin, you'll need:

* A pyck account with API access
* Authentication credentials (JWT token or PAT)
* A GraphQL client or HTTP client

## Making Your First Query

Let's start with a simple query to get information about the current user:

```graphql
query {
  me {
    id
    name
    email
  }
}
```

This query requests the ID, name, and email of the authenticated user.

### Using curl

```bash
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  --data '{"query": "query { me { id name email } }"}' \
  https://api.pyck.ai/graphql
```

### Using JavaScript

```javascript
async function fetchCurrentUser() {
  const response = await fetch('https://api.pyck.ai/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      query: `
        query {
          me {
            id
            name
            email
          }
        }
      `
    })
  });

  const result = await response.json();
  return result.data.me;
}
```

## Understanding the Response

GraphQL responses always follow the same structure:

```json
{
  "data": {
    "me": {
      "id": "user-123",
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
  }
}
```

If there are errors, they'll be returned in an `errors` array:

```json
{
  "errors": [
    {
      "message": "You are not authenticated",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["me"]
    }
  ],
  "data": null
}
```

## Basic Query Examples

### Listing Inventory Items

```graphql
query {
  inventoryItems(first: 10) {
    edges {
      node {
        id
        name
        sku
      }
    }
  }
}
```

### Creating an Inventory Item

```graphql
mutation {
  createInventoryItem(input: {
    name: "Test Product"
    sku: "TP-001"
    data: { weight: 1.5, color: "blue" }
  }) {
    id
    name
    sku
    createdAt
  }
}
```

## Using Variables

GraphQL allows you to use variables for dynamic values:

```graphql
query GetItem($id: ID!) {
  node(id: $id) {
    ... on InventoryItem {
      id
      name
      sku
    }
  }
}
```

With variables:

```json
{
  "id": "item-123"
}
```

## Next Steps

Now that you've made your first queries, you can:

1. Explore the [Schema Overview](/graphql-api/schema-overview) to understand available operations
2. Learn about [Authentication](/graphql-api/authentication) for secure API access
3. Check out [Error Handling](/graphql-api/error-handling) for robust applications
4. Dive into specific query and mutation documentation

## Tools and Resources

* [GraphQL Playground](https://api.pyck.ai/graphql): Interactive API explorer
* [Apollo Client](https://www.apollographql.com/docs/react/): Popular GraphQL client for JavaScript
* [Insomnia](https://insomnia.rest/): API client with GraphQL support
* [Postman](https://learning.postman.com/docs/sending-requests/supported-api-frameworks/graphql/): API testing tool with GraphQL support


# Schema Overview

Overview of the GraphQL Schema

## Introduction

The pyck GraphQL API provides a comprehensive interface for interacting with your warehouse management system. This document gives you a high-level overview of the schema structure.

## Core Components

The schema is organized into several main sections:

### Queries

Queries allow you to fetch data from the system. Some key queries include:

* `me`: Get information about the current user
* `inventoryItems`: List inventory items with filtering and pagination
* `repositories`: List repositories (warehouses, zones, etc.)
* `stocks`: Get current or historical stock levels
* `pickingOrders`: List picking orders
* `receivingInbounds`: List inbound receiving orders

### Mutations

Mutations allow you to create, update, or delete data. Key mutations include:

* `createInventoryItem`: Create a new inventory item
* `createInventoryItemMovement`: Create a movement to transfer items
* `createInventoryRepository`: Create a new repository
* `createPickingOrder`: Create a new picking order
* `createReceivingInbound`: Create a new inbound receiving order
* `executeInventoryItemMovement`: Execute a pending movement

### Types

The schema defines numerous types that represent entities and concepts in the system:

* `InventoryItem`: Represents products and items in your inventory
* `Repository`: Represents storage locations (warehouses, zones, bins, etc.)
* `Stock`: Represents the quantity of an item in a specific repository
* `ItemMovement`: Represents the transfer of items between repositories
* `PickingOrder`: Represents an order to pick items from stock
* `ReceivingInbound`: Represents an inbound shipment to be received

## Schema Relationships

The schema includes many relationships between entities:

1. **Items and Repositories**:
   * Items are stored in repositories
   * Each repository can contain multiple items
   * Repositories can be nested (e.g., a bin within a zone)
2. **Movements and Stock**:
   * Item movements change stock levels
   * Stock records track item quantities at specific points in time
   * Movements can be grouped into collections
3. **Orders and Operations**:
   * Picking orders generate item movements to fulfill orders
   * Receiving inbounds create movements to add stock to the warehouse

## Exploring the Schema

For detailed information about specific parts of the schema, consult the dedicated documentation sections:

* [Queries](/graphql-api/queries)
* [Mutations](/graphql-api/mutations)
* [Types](/graphql-api/types)
* [Scalars](https://github.com/pyck-ai/docs/blob/main/graphql/scalars/README.md)
* [Inputs](/graphql-api/inputs)
* [Interfaces](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/README.md)


# Authentication

GraphQL API Authentication

## Overview

All GraphQL API requests to pyck must be authenticated. This document explains how to authenticate your API requests.

## Authentication Methods

The pyck GraphQL API supports two primary authentication methods:

### 1. JWT Token Authentication

JWT (JSON Web Token) authentication is the most common method and involves including a valid JWT token in the Authorization header of your requests.

```
Authorization: Bearer <your_jwt_token>
```

JWT tokens are typically obtained through the ZITADEL authentication flow. Once you have a token, include it in all your API requests.

### 2. Personal Access Token (PAT)

For system integrations and automation, you can use a Personal Access Token:

```
Authorization: Bearer <your_personal_access_token>
```

PATs are long-lived tokens that can be created through the pyck administration interface.

## Example Authentication Flow

### 1. Obtain a JWT Token

Authenticate with ZITADEL to obtain a JWT token. This typically involves redirecting the user to the ZITADEL login page and handling the callback with the token.

### 2. Make Authenticated Requests

Once you have a token, include it in your GraphQL requests:

```javascript
// Example with fetch API
const response = await fetch('https://api.pyck.ai/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    query: `
      query {
        me {
          id
          name
          email
        }
      }
    `
  })
});
```

### 3. Handle Token Expiration

JWT tokens expire after a certain period. When a token expires, you'll receive a 401 Unauthorized response. You should:

1. Detect the 401 response
2. Request a new token using the refresh token flow
3. Retry the original request with the new token

## Testing Authentication

You can test your authentication by querying the `me` endpoint, which returns information about the authenticated user:

```graphql
query {
  me {
    id
    name
    email
  }
}
```

If authentication is successful, you'll receive information about your user. If not, you'll receive an error message.


# Error Handling

GraphQL Error Handling

## Overview

Understanding how to handle errors in the pyck GraphQL API is essential for building robust applications. This document describes the error formats and best practices for handling various error conditions.

## Error Structure

GraphQL errors are returned in a standardized format as part of the response:

```json
{
  "data": { ... },  // Might be null or partial if there were errors
  "errors": [
    {
      "message": "A human-readable error message",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["query", "fieldWithError"],
      "extensions": {
        "code": "ERROR_CODE",
        "details": { ... }
      }
    }
  ]
}
```

## Common Error Codes

pyck uses standardized error codes to help you identify and handle specific error conditions:

* `UNAUTHENTICATED`: The request lacks valid authentication
* `FORBIDDEN`: The authenticated user doesn't have sufficient permissions
* `BAD_USER_INPUT`: The request contains invalid input values
* `NOT_FOUND`: The requested resource was not found
* `CONFLICT`: The operation would conflict with current state
* `INTERNAL_SERVER_ERROR`: An unexpected error occurred on the server

## Error Handling Strategies

### Authentication Errors

When you receive `UNAUTHENTICATED` errors:

* Check that you're including a valid token in the Authorization header
* Verify that the token hasn't expired
* Request a new token if needed

### Permission Errors

When you receive `FORBIDDEN` errors:

* Verify that the user has the necessary permissions
* Check if the user is trying to access resources outside their tenant
* Consider requesting additional permissions if needed

### Input Validation Errors

When you receive `BAD_USER_INPUT` errors:

* Check the `details` field in the error extensions for specifics
* Validate input data before sending it to the API
* Display helpful error messages to guide users

### Not Found Errors

When you receive `NOT_FOUND` errors:

* Verify that you're using the correct ID
* Check if the resource might have been deleted
* Consider graceful degradation or fallback options

### Conflict Errors

When you receive `CONFLICT` errors:

* Refresh your local data to see the current state
* Resolve the conflict by merging changes or taking alternative actions
* Consider optimistic UI with conflict resolution

## Error Handling Example

Here's an example of how to handle errors in a client application:

```javascript
async function executeGraphQLQuery(query, variables) {
  try {
    const response = await fetch('https://api.pyck.ai/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ query, variables })
    });

    const result = await response.json();
    
    if (result.errors) {
      // Handle different error types
      result.errors.forEach(error => {
        const code = error.extensions?.code;
        
        switch (code) {
          case 'UNAUTHENTICATED':
            // Handle authentication error (e.g., refresh token)
            refreshAuthToken();
            break;
          case 'FORBIDDEN':
            // Handle permission error
            notifyUserOfPermissionIssue(error.message);
            break;
          case 'BAD_USER_INPUT':
            // Handle validation error
            displayValidationErrors(error.extensions?.details);
            break;
          default:
            // Handle other errors
            logError(error);
            displayGenericErrorMessage();
        }
      });
    }
    
    return result.data;
  } catch (error) {
    // Handle network errors
    logError(error);
    displayNetworkErrorMessage();
    return null;
  }
}
```

## Best Practices

1. **Always check for errors**: Never assume a GraphQL response won't contain errors
2. **Handle partial data**: GraphQL can return partial data with errors for some fields
3. **Provide user feedback**: Translate error messages into actionable feedback
4. **Implement retry logic**: Automatically retry after authentication failures
5. **Log unexpected errors**: Capture detailed information for debugging


# Queries

GraphQL Queries

This section documents all available queries in the pyck GraphQL API. Queries allow you to fetch data from the system without making any changes.

## Available Queries

### Management Service

* [**devices**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/devices.md): List and filter devices (scanners, printers, terminals)
* [**deviceLocations**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/deviceLocations.md): List and filter device-location assignments
* [**deviceUsers**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/deviceUsers.md): List and filter device-user assignments
* [**locations**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/locations.md): List and filter warehouse locations
* [**companies**](/graphql-api/queries/companies): List and filter companies
* [**customers**](/graphql-api/queries/customers): List and filter customers
* [**dataTypeEntities**](/graphql-api/queries/datatypeentities): Get all available entity types for data types
* [**dataTypes**](/graphql-api/queries/datatypes): Retrieve data type definitions
* [**nodeDataType**](/graphql-api/queries/nodedatatype): Retrieve management objects by ID
* [**suppliers**](/graphql-api/queries/suppliers): List and filter suppliers
* [**users**](/graphql-api/queries/users): List and filter users
* [**me**](/graphql-api/queries/me): Get information about the current user

### Inventory Service

* [**inventoryCollections**](/graphql-api/queries/inventorycollections): List and filter inventory collections
* [**inventoryItems**](/graphql-api/queries/inventoryitems): List and filter inventory items
* [**inventoryItemSets**](/graphql-api/queries/inventoryitemsets): List and filter inventory item sets
* [**itemMovements**](/graphql-api/queries/itemmovements): List and filter item movements
* [**nodeInventory**](/graphql-api/queries/nodeinventory): Retrieve inventory objects by ID
* [**repositories**](/graphql-api/queries/repositories): List and filter repositories
* [**repositoryMovements**](/graphql-api/queries/repositorymovements): List and filter repository movements
* [**stocks**](/graphql-api/queries/stocks): Get current or historical stock levels
* [**transactions**](/graphql-api/queries/transactions): List and filter inventory transactions

### Picking Service

* [**pickingOrderItems**](/graphql-api/queries/pickingorderitems): List and filter picking order items
* [**pickingOrders**](/graphql-api/queries/pickingorders): List and filter picking orders
* [**pickingOutboundShipmentNotifications**](/graphql-api/queries/pickingoutboundshipmentnotifications): List and filter outbound shipment notifications
* [**nodePicking**](/graphql-api/queries/nodepicking): Retrieve picking objects by ID

### Receiving Service

* [**receivingInbounds**](/graphql-api/queries/receivinginbounds): List and filter receiving inbounds
* [**receivingInboundItems**](/graphql-api/queries/receivinginbounditems): List and filter receiving inbound items
* [**receivingInboundShipmentNotifications**](/graphql-api/queries/receivinginboundshipmentnotifications): List and filter inbound shipment notifications
* [**nodeReceiving**](/graphql-api/queries/nodereceiving): Retrieve receiving objects by ID

### Workflow Service

* [**assignableWorkflowExecutions**](/graphql-api/queries/assignableworkflowexecutions): List workflow executions with pending user tasks
* [**workflows**](/graphql-api/queries/workflows): List and filter workflows
* [**workflowActions**](/graphql-api/queries/workflowactions): Retrieve the queries and updates currently available for a workflow execution
* [**workflowAssignee**](/graphql-api/queries/workflowassignee): Retrieve the assignee of a specific workflow run
* [**workflowExecutions**](/graphql-api/queries/workflowexecutions): List and filter workflow executions with pagination
* [**workflowHistory**](/graphql-api/queries/workflowhistory): Fetch workflow history events
* [**workflowSignals**](/graphql-api/queries/workflowsignals): List and filter workflow signals
* [**workflowTargets**](/graphql-api/queries/workflowtargets): Read the current target surfaces of a workflow execution
* [**nodeWorkflow**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/nodeWorkflow.md): Retrieve workflow objects by ID

### File Service

* [**files**](/graphql-api/queries/files): List and filter files
* [**nodeFile**](https://github.com/pyck-ai/docs/blob/main/graphql/queries/nodeFile.md): Retrieve files by ID

### System

* [**events**](/graphql-api/queries/events): List and filter system events

## Pagination and Filtering

Most list queries support pagination using the Relay connection specification. This allows you to efficiently navigate large result sets.

Example of paginated query:

```graphql
query {
  inventoryItems(
    first: 10
    after: "cursor-value"
    where: { 
      name: { contains: "product" }
    }
    orderBy: { createdAt: DESC }
  ) {
    edges {
      node {
        id
        name
        sku
      }
      cursor
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    totalCount
  }
}
```

## Common Query Parameters

Many queries support similar parameters:

* `where`: Filter criteria specific to the queried entity
* `orderBy`: Sorting criteria for the results
* Pagination parameters: `first`, `after`, `last`, `before`


# Node Queries


# NodeAttachments

nodeAttachments Query

Audience: Programmer

Fetches an attachment object given its ID. This query follows the Relay Global Object Identification Specification and is used to retrieve a single attachment by its unique identifier.

## Arguments

| Name | Type  | Description                                         |
| ---- | ----- | --------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the attachment to retrieve |

## Return Type

`NodeAttachments` - An interface that returns an object implementing the NodeAttachments interface. Currently, this is implemented by the `Attachment` type.

## Usage Example

### GraphQL Query

```graphql
query GetAttachment($id: ID!) {
  nodeAttachments(id: $id) {
    id
    ... on Attachment {
      filename
      contentType
      size
      url
      refId
      reftype
      metadata
      createdAt
      updatedAt
    }
  }
}
```

### Query Variables

```json
{
  "id": "QXR0YWNobWVudDoxMjM="
}
```

### JavaScript Example

```javascript
const getAttachment = async (attachmentId) => {
  const query = `
    query GetAttachment($id: ID!) {
      nodeAttachments(id: $id) {
        id
        ... on Attachment {
          filename
          contentType
          size
          url
          refId
          reftype
          metadata
          createdAt
          updatedAt
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: attachmentId }
    })
  });

  const { data } = await response.json();
  return data.nodeAttachments;
};
```

## Related

* [Attachment Type](https://github.com/pyck-ai/docs/blob/main/graphql/types/Attachment.md)
* [attachments Query](/graphql-api/queries/attachments)
* [createAttachment Mutation](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/createAttachment.md)
* [NodeAttachments Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodeAttachments.md)


# NodeInventory

nodeInventory Query

Audience: Programmer

Fetches an inventory-related object given its ID. This query follows the Relay Global Object Identification Specification and can retrieve any object that implements the NodeInventory interface.

## Arguments

| Name | Type  | Description                                               |
| ---- | ----- | --------------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the inventory object to retrieve |

## Return Type

`NodeInventory` - An interface that returns an object implementing the NodeInventory interface. This includes:

* `InventoryItem` - Product or item in inventory
* `Repository` - Storage location (warehouse, bin, pallet, etc.)
* `Stock` - Inventory levels
* `ItemMovement` - Movement of items between repositories
* `RepositoryMovement` - Movement of entire repositories
* `Transaction` - Inventory transaction records
* `InventoryCollection` - Collection of inventory items
* `InventoryItemSet` - Set of related inventory items

## Usage Example

### GraphQL Query

```graphql
query GetInventoryObject($id: ID!) {
  nodeInventory(id: $id) {
    id
    ... on InventoryItem {
      sku
      data
      inventoryJSONData
      itemmovementitem {
        edges {
          node {
            id
            quantity
            status
          }
        }
      }
    }
    ... on Repository {
      name
      type
      repositorySystemData
      repositorystocks {
        edges {
          node {
            item {
              sku
            }
            quantity
          }
        }
      }
    }
    ... on Stock {
      quantity
      timestamp
      item {
        sku
      }
      repository {
        name
      }
    }
    ... on ItemMovement {
      quantity
      status
      sourceRepository {
        name
      }
      destinationRepository {
        name
      }
      item {
        sku
      }
    }
  }
}
```

### Query Variables

```json
{
  "id": "SW52ZW50b3J5SXRlbToxMjM="
}
```

### JavaScript Example

```javascript
const getInventoryObject = async (objectId) => {
  const query = `
    query GetInventoryObject($id: ID!) {
      nodeInventory(id: $id) {
        id
        __typename
        ... on InventoryItem {
          sku
          data
          createdAt
          updatedAt
        }
        ... on Repository {
          name
          type
          repositorySystemData
        }
        ... on Stock {
          quantity
          timestamp
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: objectId }
    })
  });

  const { data } = await response.json();
  return data.nodeInventory;
};
```

## Type Detection

Use the `__typename` field to determine which specific type was returned:

```javascript
const object = await getInventoryObject(id);
switch (object.__typename) {
  case 'InventoryItem':
    console.log(`Item SKU: ${object.sku}`);
    break;
  case 'Repository':
    console.log(`Repository: ${object.name}`);
    break;
  case 'Stock':
    console.log(`Stock quantity: ${object.quantity}`);
    break;
  // ... handle other types
}
```

## Related

* [NodeInventory Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodeInventory.md)
* [InventoryItem Type](/graphql-api/types/inventoryitem)
* [Repository Type](/graphql-api/types/repository)
* [Stock Type](/graphql-api/types/stock)
* [inventoryItems Query](/graphql-api/queries/inventoryitems)
* [repositories Query](/graphql-api/queries/repositories)


# NodeDataType

nodeDataType Query

Audience: Programmer

Fetches a management-related object given its ID. This query follows the Relay Global Object Identification Specification and can retrieve any object that implements the NodeDataType interface.

## Arguments

| Name | Type  | Description                                                |
| ---- | ----- | ---------------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the management object to retrieve |

## Return Type

`NodeDataType` - An interface that returns an object implementing the NodeDataType interface. This includes:

* `DataType` - JSON schema definition for entity data validation
* `Company` - Company/organization entity
* `Event` - Custom event definitions
* `User` - System user accounts

## Usage Example

### GraphQL Query

```graphql
query GetManagementObject($id: ID!) {
  nodeDataType(id: $id) {
    id
    ... on DataType {
      name
      slug
      schema
      entity
      enabled
      createdAt
      updatedAt
    }
    ... on Company {
      name
      organizationID
      tenantID
      users {
        id
        username
        email
      }
    }
    ... on Event {
      topic
      name
      description
      payload
      key
      createdAt
    }
    ... on User {
      username
      email
      idpID
      role
      groups {
        id
        name
      }
      company {
        name
      }
    }
  }
}
```

### Query Variables

```json
{
  "id": "RGF0YVR5cGU6MTIz"
}
```

### JavaScript Example

```javascript
const getManagementObject = async (objectId) => {
  const query = `
    query GetManagementObject($id: ID!) {
      nodeDataType(id: $id) {
        id
        __typename
        ... on DataType {
          name
          slug
          schema
          entity
          enabled
        }
        ... on Company {
          name
          organizationID
          tenantID
        }
        ... on User {
          username
          email
          role
        }
        ... on Event {
          topic
          name
          description
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: objectId }
    })
  });

  const { data } = await response.json();
  return data.nodeDataType;
};
```

## Type Detection

Use the `__typename` field to determine which specific type was returned:

```javascript
const object = await getManagementObject(id);
switch (object.__typename) {
  case 'DataType':
    console.log(`DataType: ${object.name} (${object.slug})`);
    break;
  case 'Company':
    console.log(`Company: ${object.name}`);
    break;
  case 'User':
    console.log(`User: ${object.username} (${object.email})`);
    break;
  case 'Event':
    console.log(`Event: ${object.topic} - ${object.name}`);
    break;
}
```

## Related

* [NodeDataType Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodeDataType.md)
* [DataType Type](/graphql-api/types/datatype)
* [Company Type](/graphql-api/types/company)
* [User Type](/graphql-api/types/user)
* [Event Type](/graphql-api/types/event)
* [dataTypes Query](/graphql-api/queries/datatypes)
* [companies Query](/graphql-api/queries/companies)
* [users Query](/graphql-api/queries/users)
* [events Query](/graphql-api/queries/events)


# NodePicking

nodePicking Query

Audience: Programmer

Fetches a picking-related object given its ID. This query follows the Relay Global Object Identification Specification and can retrieve any object that implements the NodePicking interface.

## Arguments

| Name | Type  | Description                                             |
| ---- | ----- | ------------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the picking object to retrieve |

## Return Type

`NodePicking` - An interface that returns an object implementing the NodePicking interface. This includes:

* `PickingOrder` - A picking order containing items to be picked
* `PickingOrderItem` - Individual item within a picking order

## Usage Example

### GraphQL Query

```graphql
query GetPickingObject($id: ID!) {
  nodePicking(id: $id) {
    id
    ... on PickingOrder {
      name
      status
      type
      data
      pickingSystemData
      createdAt
      updatedAt
      pickingorderitems {
        edges {
          node {
            id
            quantity
            status
            item {
              sku
            }
          }
        }
      }
    }
    ... on PickingOrderItem {
      quantity
      status
      item {
        sku
        data
      }
      pickingOrder {
        name
        status
      }
    }
  }
}
```

### Query Variables

```json
{
  "id": "UGlja2luZ09yZGVyOjEyMw=="
}
```

### JavaScript Example

```javascript
const getPickingObject = async (objectId) => {
  const query = `
    query GetPickingObject($id: ID!) {
      nodePicking(id: $id) {
        id
        __typename
        ... on PickingOrder {
          name
          status
          type
          data
          createdAt
          updatedAt
        }
        ... on PickingOrderItem {
          quantity
          status
          item {
            sku
          }
          pickingOrder {
            name
          }
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: objectId }
    })
  });

  const { data } = await response.json();
  return data.nodePicking;
};
```

## Type Detection

Use the `__typename` field to determine which specific type was returned:

```javascript
const object = await getPickingObject(id);
switch (object.__typename) {
  case 'PickingOrder':
    console.log(`Picking Order: ${object.name}`);
    break;
  case 'PickingOrderItem':
    console.log(`Order Item SKU: ${object.item.sku}`);
    break;
}
```

## Related

* [NodePicking Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodePicking.md)
* [PickingOrder Type](/graphql-api/types/pickingorder)
* [PickingOrderItem Type](/graphql-api/types/pickingorderitem)
* [pickingOrders Query](/graphql-api/queries/pickingorders)


# NodeReceiving

nodeReceiving Query

Audience: Programmer

Fetches a receiving-related object given its ID. This query follows the Relay Global Object Identification Specification and can retrieve any object that implements the NodeReceiving interface.

## Arguments

| Name | Type  | Description                                               |
| ---- | ----- | --------------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the receiving object to retrieve |

## Return Type

`NodeReceiving` - An interface that returns an object implementing the NodeReceiving interface. This includes:

* `ReceivingInbound` - An inbound receiving order containing items to be received
* `ReceivingInboundItem` - Individual item within a receiving inbound order

## Usage Example

### GraphQL Query

```graphql
query GetReceivingObject($id: ID!) {
  nodeReceiving(id: $id) {
    id
    ... on ReceivingInbound {
      name
      status
      type
      data
      receivingSystemData
      createdAt
      updatedAt
      receivinginbounditems {
        edges {
          node {
            id
            quantity
            status
            item {
              sku
            }
          }
        }
      }
    }
    ... on ReceivingInboundItem {
      quantity
      status
      item {
        sku
        data
      }
      receivingInbound {
        name
        status
      }
    }
  }
}
```

### Query Variables

```json
{
  "id": "UmVjZWl2aW5nSW5ib3VuZDoxMjM="
}
```

### JavaScript Example

```javascript
const getReceivingObject = async (objectId) => {
  const query = `
    query GetReceivingObject($id: ID!) {
      nodeReceiving(id: $id) {
        id
        __typename
        ... on ReceivingInbound {
          name
          status
          type
          data
          createdAt
          updatedAt
        }
        ... on ReceivingInboundItem {
          quantity
          status
          item {
            sku
          }
          receivingInbound {
            name
          }
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: objectId }
    })
  });

  const { data } = await response.json();
  return data.nodeReceiving;
};
```

## Type Detection

Use the `__typename` field to determine which specific type was returned:

```javascript
const object = await getReceivingObject(id);
switch (object.__typename) {
  case 'ReceivingInbound':
    console.log(`Receiving Inbound: ${object.name}`);
    break;
  case 'ReceivingInboundItem':
    console.log(`Inbound Item SKU: ${object.item.sku}`);
    break;
}
```

## Related

* [NodeReceiving Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodeReceiving.md)
* [ReceivingInbound Type](/graphql-api/types/receivinginbound)
* [ReceivingInboundItem Type](/graphql-api/types/receivinginbounditem)
* [receivingInbounds Query](/graphql-api/queries/receivinginbounds)


# NodeWorkflowService

nodeWorkflowService Query

Audience: Programmer

Fetches a workflow-related object given its ID. This query follows the Relay Global Object Identification Specification and can retrieve any object that implements the NodeWorkflowService interface.

## Arguments

| Name | Type  | Description                                              |
| ---- | ----- | -------------------------------------------------------- |
| `id` | `ID!` | The unique identifier of the workflow object to retrieve |

## Return Type

`NodeWorkflowService` - An interface that returns an object implementing the NodeWorkflowService interface. This includes:

* `Workflow` - A Temporal workflow instance with execution details
* `WorkflowSignal` - A signal that can be sent to a running workflow

## Usage Example

### GraphQL Query

```graphql
query GetWorkflowObject($id: ID!) {
  nodeWorkflowService(id: $id) {
    id
    ... on Workflow {
      workflowID
      runID
      workflowType
      status
      startTime
      endTime
      execution
      searchAttributes
      createdAt
      updatedAt
    }
    ... on WorkflowSignal {
      signalName
      workflowID
      runID
      payload
      status
      createdAt
      updatedAt
    }
  }
}
```

### Query Variables

```json
{
  "id": "V29ya2Zsb3c6MTIz"
}
```

### JavaScript Example

```javascript
const getWorkflowObject = async (objectId) => {
  const query = `
    query GetWorkflowObject($id: ID!) {
      nodeWorkflowService(id: $id) {
        id
        __typename
        ... on Workflow {
          workflowID
          runID
          workflowType
          status
          startTime
          endTime
          execution
        }
        ... on WorkflowSignal {
          signalName
          workflowID
          runID
          payload
          status
        }
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { id: objectId }
    })
  });

  const { data } = await response.json();
  return data.nodeWorkflowService;
};
```

## Type Detection

Use the `__typename` field to determine which specific type was returned:

```javascript
const object = await getWorkflowObject(id);
switch (object.__typename) {
  case 'Workflow':
    console.log(`Workflow: ${object.workflowID} (${object.status})`);
    break;
  case 'WorkflowSignal':
    console.log(`Signal: ${object.signalName} for workflow ${object.workflowID}`);
    break;
}
```

## Common Use Cases

### Monitor Workflow Status

```javascript
const checkWorkflowStatus = async (workflowId) => {
  const workflow = await getWorkflowObject(workflowId);
  if (workflow.__typename === 'Workflow') {
    return {
      id: workflow.workflowID,
      status: workflow.status,
      isRunning: workflow.status === 'Running',
      isCompleted: workflow.status === 'Completed',
      duration: workflow.endTime ? 
        new Date(workflow.endTime) - new Date(workflow.startTime) : null
    };
  }
};
```

## Related

* [NodeWorkflowService Interface](https://github.com/pyck-ai/docs/blob/main/graphql/interfaces/NodeWorkflowService.md)
* [Workflow Type](/graphql-api/types/workflow)
* [WorkflowSignal Type](/graphql-api/types/workflowsignal)
* [Temporal Workflow Documentation](/development/workflows)


# Attachments

attachments Query

Audience: Programmer

Retrieves a paginated list of attachments with support for filtering and ordering. This query returns all attachments across the system that the user has access to.

## Arguments

| Name      | Type                   | Description                                                          |
| --------- | ---------------------- | -------------------------------------------------------------------- |
| `after`   | `Cursor`               | Returns elements after the specified cursor for forward pagination   |
| `first`   | `Int`                  | Returns the first n elements from the list                           |
| `before`  | `Cursor`               | Returns elements before the specified cursor for backward pagination |
| `last`    | `Int`                  | Returns the last n elements from the list                            |
| `orderBy` | `AttachmentOrder`      | Ordering options for the returned attachments                        |
| `where`   | `AttachmentWhereInput` | Filtering criteria for the attachments                               |

## Return Type

`AttachmentConnection!` - A Relay-style connection containing:

* `edges`: Array of attachment edges with cursor information
* `nodes`: Array of attachment objects
* `pageInfo`: Information about pagination (hasNextPage, hasPreviousPage, etc.)
* `totalCount`: Total number of attachments matching the filter

## Usage Example

### GraphQL Query

```graphql
query GetAttachments($first: Int!, $where: AttachmentWhereInput) {
  attachments(first: $first, where: $where) {
    edges {
      node {
        id
        filename
        contentType
        size
        url
        createdAt
        updatedAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    totalCount
  }
}
```

### Query Variables

```json
{
  "first": 20,
  "where": {
    "contentType": {
      "startsWith": "image/"
    }
  }
}
```

### JavaScript Example

```javascript
const getAttachments = async (limit = 20, filters = {}) => {
  const query = `
    query GetAttachments($first: Int!, $where: AttachmentWhereInput) {
      attachments(first: $first, where: $where) {
        edges {
          node {
            id
            filename
            contentType
            size
            url
            createdAt
          }
          cursor
        }
        pageInfo {
          hasNextPage
          endCursor
        }
        totalCount
      }
    }
  `;

  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      query,
      variables: { 
        first: limit,
        where: filters
      }
    })
  });

  const { data } = await response.json();
  return data.attachments;
};

// Get all image attachments
const images = await getAttachments(20, {
  contentType: { startsWith: "image/" }
});

// Get attachments created in the last week
const recent = await getAttachments(10, {
  createdAt: { 
    gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
  }
});
```

## Filtering Options

The `where` parameter supports various filtering options:

```javascript
// Filter by content type
{
  contentType: { 
    equals: "application/pdf",
    startsWith: "image/",
    in: ["image/jpeg", "image/png"]
  }
}

// Filter by filename
{
  filename: {
    contains: "report",
    startsWith: "invoice_"
  }
}

// Filter by file size
{
  size: {
    gte: 1024,      // Greater than or equal to 1KB
    lte: 10485760   // Less than or equal to 10MB
  }
}

// Filter by creation date
{
  createdAt: {
    gte: "2024-01-01T00:00:00Z",
    lte: "2024-12-31T23:59:59Z"
  }
}
```

## Ordering Options

Sort attachments using the `orderBy` parameter:

```javascript
// Sort by creation date (newest first)
{ createdAt: "DESC" }

// Sort by filename (alphabetical)
{ filename: "ASC" }

// Sort by file size (largest first)
{ size: "DESC" }
```

## Related

* [nodeAttachments Query](/graphql-api/queries/nodeattachments)
* [Attachment Type](https://github.com/pyck-ai/docs/blob/main/graphql/types/Attachment.md)
* [File Management Guide](https://github.com/pyck-ai/docs/blob/main/development/file-management.md)


# Companies

Companies Query

Returns a paginated list of Company objects, with optional filtering and ordering.

## Arguments

| Name      | Type                | Description                                                            |
| --------- | ------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`            | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`               | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`            | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`               | Returns the last *n* elements from the list                            |
| `orderBy` | `CompanyOrder`      | Ordering options for companies returned from the connection            |
| `where`   | `CompanyWhereInput` | Filtering options for companies returned from the connection           |

## Return Type

`CompanyConnection!` - A connection to a list of Company objects with pagination information.

## Usage Example

```graphql
query {
  # Search companies by name
  companies(
    where: {
      nameContains: "Tech"
    },
    orderBy: { direction: ASC, field: NAME }
  ) {
    edges {
      node {
        id
        name
        organizationID
        tenantID
        createdAt
        companyusers {
          id
          name
          email
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get companies for specific organization
  companies(
    where: {
      organizationID: "org-123"
    },
    first: 20
  ) {
    edges {
      node {
        id
        name
        organizationID
        tenantID
        companyusers {
          id
          name
          email
        }
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

## Common Filters

* `nameContains` - Search by company name substring
* `name` - Find by exact company name
* `organizationID` - Filter by organization ID
* `tenantID` - Filter by tenant ID
* `hasCompanyUsers` - Filter companies that have users
* `hasCompanyUsersWith` - Filter by user criteria

## Notes

* Companies represent organizations within the pyck system
* Each company belongs to a tenant and organization
* Companies can have multiple users associated with them
* Support for multi-tenant architecture through tenantID field
* organizationID links companies to external organization systems


# Customers

Customers Query

Returns a paginated list of Customer objects, with optional filtering and ordering.

## Arguments

| Name      | Type                 | Description                                                            |
| --------- | -------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`             | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`             | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                | Returns the last *n* elements from the list                            |
| `orderBy` | `CustomerOrder`      | Ordering options for customers returned from the connection            |
| `where`   | `CustomerWhereInput` | Filtering options for customers returned from the connection           |

## Return Type

`CustomerConnection!` - A connection to a list of Customer objects with pagination information.

## Notes

* The `data` field contains custom attributes as JSON
* Use `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters for querying JSON data
* See [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md) for detailed JSON query examples

## Usage Example

```graphql
query {
  # Search customers by name
  customers(
    where: {
      name_CONTAINS: "Corp"
    },
    orderBy: { direction: ASC, field: NAME }
  ) {
    edges {
      node {
        id
        name
        code
        email
        data
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get customers with recent orders
  customers(
    where: {
      pickingOrders_SOME: {
        createdAt_GTE: "2024-01-01T00:00:00Z"
      }
    },
    first: 20
  ) {
    edges {
      node {
        id
        name
        pickingOrders {
          id
          createdAt
          orderitems {
            quantity
            item {
              sku
            }
          }
        }
      }
    }
  }
}
```

## Common Filters

* `name_CONTAINS` - Search by customer name
* `code` - Find by exact customer code
* `email` - Find by email address
* `dataTypeSlug` - Filter by customer type
* `pickingOrders_SOME` - Filter by order criteria

## Notes

* Customers are linked to picking orders
* Support custom fields through data/dataType
* Can represent both individuals and organizations
* Use virtual repositories named after customers for shipping


# Data Types

dataTypes Query

Returns a paginated list of DataType objects, with optional filtering and ordering.

## Arguments

| Name      | Type                 | Description                                                            |
| --------- | -------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`             | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`             | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                | Returns the last *n* elements from the list                            |
| `orderBy` | `DataTypeOrder`      | Ordering options for DataTypes returned from the connection            |
| `where`   | `DataTypeWhereInput` | Filtering options for DataTypes returned from the connection           |

## Return Type

`DataTypeConnection!` - A connection to a list of DataType objects with pagination information.

## Usage Example

```graphql
query {
  # Get all data types for a specific entity
  dataTypes(
    where: {
      entity: "item"
    },
    orderBy: { direction: ASC, field: NAME }
  ) {
    edges {
      node {
        id
        name
        slug
        description
        entity
        default
        jsonSchema
        frontendSchema
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get all default data types
  dataTypes(
    where: {
      default: true
    }
  ) {
    edges {
      node {
        id
        name
        entity
        slug
        jsonSchema
      }
    }
    totalCount
  }
} 
```


# DataTypeEntities

Data Type Entities Query

Returns a list of all available entity types that can have custom data types defined for them in the pyck system.

## Arguments

This query takes no arguments.

## Return Type

`[String!]` - A non-null array of string values representing entity names.

## Usage Example

```graphql
query {
  dataTypeEntities
}
```

**Response:**

```json
{
  "data": {
    "dataTypeEntities": [
      "item",
      "customer", 
      "supplier",
      "picking_order",
      "picking_order_item",
      "inbound",
      "inbound_item",
      "item_movement",
      "repository_movement",
      "file",
      "item_set",
      "repository",
      "collection_movement"
    ]
  }
}
```

## Usage with Data Types

```graphql
query {
  # Get all available entity types
  dataTypeEntities
  
  # Then get data types for a specific entity
  dataTypes(
    where: {
      entity: "item"
    }
  ) {
    edges {
      node {
        id
        name
        slug
        entity
        jsonSchema
      }
    }
  }
}
```

## Notes

* This query returns all entity types that support custom data type definitions
* Use this to understand which entities can have custom fields and schemas
* Essential for building dynamic forms and custom field management interfaces
* The returned strings correspond to entity names used in the `entity` field of DataType objects
* These entities represent core business objects in the pyck warehouse management system


# Events

Events Query

Returns a paginated list of Event objects, with optional filtering and ordering. Events represent system events that can be published to NATS messaging system.

## Arguments

| Name      | Type              | Description                                                            |
| --------- | ----------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`          | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`             | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`          | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`             | Returns the last *n* elements from the list                            |
| `orderBy` | `EventOrder`      | Ordering options for events returned from the connection               |
| `where`   | `EventWhereInput` | Filtering options for events returned from the connection              |

## Return Type

`EventConnection!` - A connection to a list of Event objects with pagination information.

## Usage Example

```graphql
query {
  # Search events by topic
  events(
    where: {
      topicContains: "inventory"
    },
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        topic
        name
        description
        example
        createdAt
        createdBy
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get events created recently
  events(
    where: {
      createdAtGTE: "2024-01-01T00:00:00Z"
    },
    first: 20
  ) {
    edges {
      node {
        id
        topic
        name
        description
        example
        createdAt
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

```graphql
query {
  # Find specific event by name
  events(
    where: {
      nameContains: "item_created"
    }
  ) {
    edges {
      node {
        id
        topic
        name
        description
        example
      }
    }
  }
}
```

## Common Filters

* `topicContains` - Search by NATS topic substring
* `topic` - Find by exact topic name
* `nameContains` - Search by event name substring
* `name` - Find by exact event name
* `descriptionContains` - Search by description content
* `createdAtGTE` / `createdAtLTE` - Filter by creation date range

## Notes

* Events define the structure and metadata for system messages
* Each event has a NATS topic for message routing
* Example field contains sample payload structure
* Events are used for inter-service communication and workflow triggers
* Support audit trail through creation and update timestamps
* Essential for event-driven architecture and real-time notifications


# Files

files Query

Returns a paginated list of File objects, with optional filtering and ordering.

## Arguments

| Name      | Type             | Description                                                            |
| --------- | ---------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`         | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`            | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`         | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`            | Returns the last *n* elements from the list                            |
| `orderBy` | `FileOrder`      | Ordering options for Files returned from the connection                |
| `where`   | `FileWhereInput` | Filtering options for Files returned from the connection               |

## Return Type

`FileConnection!` - A connection to a list of File objects with pagination information.

## Usage Example

```graphql
query {
  files(
    first: 10
    orderBy: { direction: DESC, field: CREATED_AT }
    where: { reftype: item }
  ) {
    edges {
      node {
        id
        name
        contentType
        size
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```


# Inventory Collections

Inventory Collections Query

Returns a paginated list of InventoryCollection objects, with optional filtering and ordering.

## Arguments

| Name      | Type                            | Description                                                            |
| --------- | ------------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                        | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                           | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                        | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                           | Returns the last *n* elements from the list                            |
| `orderBy` | `InventoryCollectionOrder`      | Ordering options for collections returned from the connection          |
| `where`   | `InventoryCollectionWhereInput` | Filtering options for collections returned from the connection         |

## Return Type

`InventoryCollectionConnection!` - A connection to a list of InventoryCollection objects with pagination information.

## Notes

* The `data` field contains custom collection attributes as JSON
* Use `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters for querying JSON data
* See [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md) for detailed JSON query examples

## Usage Example

```graphql
query {
  # Get active collection movements
  inventoryCollections(
    where: {
      status_IN: [PENDING, IN_PROGRESS]
    },
    orderBy: { direction: ASC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        name
        status
        createdAt
        executionOrder
        itemMovements {
          id
          quantity
          executedAt
          item {
            sku
          }
          fromRepository {
            name
          }
          toRepository {
            name
          }
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get completed collections for today
  inventoryCollections(
    where: {
      status: COMPLETED,
      completedAt_GTE: "2024-01-15T00:00:00Z",
      completedAt_LTE: "2024-01-15T23:59:59Z"
    },
    first: 50
  ) {
    edges {
      node {
        id
        name
        completedAt
        completedBy
        data
        itemMovements {
          id
          quantity
        }
        repositoryMovements {
          id
        }
      }
    }
  }
}
```

## Common Filters

* `status` - Filter by collection status (PENDING, IN\_PROGRESS, COMPLETED, CANCELLED)
* `createdBy` - Filter by creator
* `completedAt_NULL: true` - Find incomplete collections
* `name_CONTAINS` - Search by collection name

## Notes

* Collections enable complex multi-step operations
* Movements execute in order specified by `executionOrder`
* Can track progress through partially completed collections
* Useful for wave picking, cross-docking, and complex transfers


# Inventory Items

Inventory Items Query

Returns a paginated list of InventoryItem objects, with optional filtering and ordering.

## Arguments

| Name      | Type                      | Description                                                            |
| --------- | ------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                  | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                     | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                  | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                     | Returns the last *n* elements from the list                            |
| `orderBy` | `InventoryItemOrder`      | Ordering options for InventoryItems returned from the connection       |
| `where`   | `InventoryItemWhereInput` | Filtering options for InventoryItems returned from the connection      |

## Return Type

`InventoryItemConnection!` - A connection to a list of InventoryItem objects with pagination information.

## Notes

* The `data` field contains custom item attributes as JSON
* Use `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters for querying JSON data
* See [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md) for detailed JSON query examples

## Usage Example

```graphql
query {
  inventoryItems(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      skuContains: "PRODUCT",
      dataTypeSlug: "physical_product"
    }
  ) {
    edges {
      node {
        id
        sku
        data
        itemstocks {
          repositoryID
          quantity
          ownQuantity
          incomingStock
          outgoingStock
        }
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```


# Inventory Item Sets

Inventory Item Sets Query

Returns a paginated list of InventoryItemSet objects, with optional filtering and ordering. Item sets allow grouping multiple inventory items together for collective operations.

## Arguments

| Name      | Type                         | Description                                                            |
| --------- | ---------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                     | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                        | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                     | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                        | Returns the last *n* elements from the list                            |
| `orderBy` | `InventoryItemSetOrder`      | Ordering options for item sets returned from the connection            |
| `where`   | `InventoryItemSetWhereInput` | Filtering options for item sets returned from the connection           |

## Return Type

`InventoryItemSetConnection!` - A connection to a list of InventoryItemSet objects with pagination information.

## Notes

The `data` field contains custom item set attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  # Search item sets by SKU
  inventoryItemSets(
    where: {
      skuContains: "BUNDLE"
    },
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        sku
        dataTypeSlug
        data
        createdAt
        items {
          id
          sku
          data
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get item sets with specific data type
  inventoryItemSets(
    where: {
      dataTypeSlug: "product_bundle"
    },
    first: 20
  ) {
    edges {
      node {
        id
        sku
        dataTypeSlug
        data
        items {
          id
          sku
          inventoryJSONData
        }
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

```graphql
query {
  # Get item sets that contain specific items
  inventoryItemSets(
    where: {
      hasItemsWith: [
        { skuContains: "COMP-001" }
      ]
    }
  ) {
    edges {
      node {
        id
        sku
        items {
          id
          sku
        }
      }
    }
  }
}
```

## Common Filters

* `skuContains` - Search by item set SKU substring
* `sku` - Find by exact item set SKU
* `dataTypeSlug` - Filter by data type slug
* `hasItems` - Filter item sets that have items
* `hasItemsWith` - Filter by criteria on contained items
* `createdAtGTE` / `createdAtLTE` - Filter by creation date range

## Notes

* Item sets represent grouped collections of inventory items
* Useful for managing product bundles, kits, or component sets
* Each item set has its own SKU for identification and tracking
* Support custom fields through data/dataType system
* Items in a set can be managed collectively for operations
* Enable complex inventory relationships and hierarchies


# Item Movements

Item Movements Query

Returns a paginated list of ItemMovement objects, with optional filtering and ordering.

## Arguments

| Name      | Type                     | Description                                                            |
| --------- | ------------------------ | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                 | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                    | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                 | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                    | Returns the last *n* elements from the list                            |
| `orderBy` | `ItemMovementOrder`      | Ordering options for movements returned from the connection            |
| `where`   | `ItemMovementWhereInput` | Filtering options for movements returned from the connection           |

## Return Type

`ItemMovementConnection!` - A connection to a list of ItemMovement objects with pagination information.

## Usage Example

```graphql
query {
  # Get all pending movements for a specific item
  itemMovements(
    where: {
      itemID: "item-123",
      executedAt_NULL: true
    },
    orderBy: { direction: ASC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        quantity
        fromRepositoryID
        toRepositoryID
        fromRepository {
          id
          name
        }
        toRepository {
          id
          name
        }
        item {
          sku
          data
        }
        blockedBy
        createdAt
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get blocked movements that need attention
  itemMovements(
    where: {
      blockedBy_NOT_NULL: true,
      executedAt_NULL: true
    },
    first: 20
  ) {
    edges {
      node {
        id
        quantity
        blockedBy
        item {
          id
          sku
        }
        fromRepository {
          id
          name
        }
        toRepository {
          id
          name
        }
        createdAt
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

## Common Filters

* `executedAt_NULL: true` - Find pending movements
* `executedAt_NOT_NULL: true` - Find executed movements
* `blockedBy_NOT_NULL: true` - Find blocked movements
* `collectionID: "..."` - Find movements in a specific collection
* `fromRepositoryID` / `toRepositoryID` - Filter by source/destination
* `itemID` - Filter by specific item

## Notes

* Movements are created in pending state and executed later
* Use `executeInventoryItemMovement` mutation to execute a movement
* Blocked movements indicate issues like insufficient stock
* Virtual repositories bypass stock validation


# Me

Current User Query

Audience: Programmer

Returns the user profile of the currently authenticated user, including tenant associations and role assignments.

## Arguments

This query does not take any arguments.

## Return Type

`UserProfile!` - The user profile of the currently authenticated user.

## Usage Example

```graphql
query {
  me {
    UserID
    Username
    Email
    FirstName
    LastName
    TenantID
    TenantName
    # Recommended: Use Tenants for multi-tenant access
    Tenants {
      ID
      Name
      Role
    }
    # Deprecated: Use Tenants instead
    AssignedRoles {
      Role
      TenantID
    }
  }
}
```

## Response Example

```json
{
  "data": {
    "me": {
      "UserID": "550e8400-e29b-41d4-a716-446655440000",
      "Username": "john.doe",
      "Email": "john.doe@example.com",
      "FirstName": "John",
      "LastName": "Doe",
      "TenantID": "123e4567-e89b-12d3-a456-426614174000",
      "TenantName": "Acme Corporation",
      "Tenants": [
        {
          "ID": "123e4567-e89b-12d3-a456-426614174000",
          "Name": "Acme Corporation",
          "Role": "admin"
        },
        {
          "ID": "987f6543-a21b-34c5-d678-123456789012",
          "Name": "Beta Industries",
          "Role": "viewer"
        }
      ]
    }
  }
}
```

## Multi-Tenant Support

The `me` query now supports multi-tenant scenarios through the `Tenants` field:

* **Primary Tenant**: The `TenantID` and `TenantName` fields represent the user's primary tenant
* **All Tenants**: The `Tenants` array contains all accessible tenants with their respective roles
* **Role Isolation**: Each tenant association has its own role assignment

## Field Deprecation

The `AssignedRoles` field is deprecated. Use the `Tenants` field instead:

```graphql
# Old approach (deprecated)
query {
  me {
    AssignedRoles {
      Role
      TenantID
    }
  }
}

# New approach (recommended)
query {
  me {
    Tenants {
      ID
      Name
      Role
    }
  }
}
```

## Common Use Cases

* **Session Initialization**: Retrieve user profile on application startup
* **Tenant Selection**: Display available tenants for user switching
* **Authorization**: Check user roles for the active tenant
* **Profile Display**: Show user information in the application header
* **Audit Context**: Capture user details for logging

## Security Notes

* This query requires authentication
* Returns only the profile of the authenticated user
* Cannot be used to retrieve other users' profiles
* Tenant data is filtered based on user permissions


# Picking Order Items

pickingOrderItems Query

Audience: Programmers

Returns a paginated list of PickingOrderItem objects, with optional filtering and ordering. This query allows you to retrieve individual line items from picking orders across the system.

## Arguments

| Name      | Type                         | Description                                                            |
| --------- | ---------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                     | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                        | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                     | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                        | Returns the last *n* elements from the list                            |
| `orderBy` | `PickingOrderItemOrder`      | Ordering options for PickingOrderItems returned from the connection    |
| `where`   | `PickingOrderItemWhereInput` | Filtering options for PickingOrderItems returned from the connection   |

## Return Type

`PickingOrderItemConnection!` - A connection to a list of PickingOrderItem objects with pagination information.

## Fields Available

The `PickingOrderItem` type includes:

| Field          | Type            | Description                                        |
| -------------- | --------------- | -------------------------------------------------- |
| `id`           | `ID!`           | Unique identifier for the order item               |
| `tenantID`     | `UUID!`         | Tenant identifier                                  |
| `orderID`      | `ID!`           | ID of the associated picking order                 |
| `quantity`     | `Int!`          | Quantity of the item to be picked                  |
| `sku`          | `String!`       | Stock keeping unit identifier                      |
| `dataTypeID`   | `UUID`          | Optional data type ID for custom validation        |
| `dataTypeSlug` | `String`        | Optional data type slug for custom validation      |
| `data`         | `Map`           | Custom data associated with the order item as JSON |
| `createdAt`    | `Time!`         | When the order item was created                    |
| `createdBy`    | `UUID!`         | User who created the order item                    |
| `updatedAt`    | `Time`          | When the order item was last updated               |
| `updatedBy`    | `UUID`          | User who last updated the order item               |
| `deletedAt`    | `Time`          | Soft deletion timestamp                            |
| `deletedBy`    | `UUID`          | User who deleted the order item                    |
| `order`        | `PickingOrder!` | The associated picking order                       |

## Notes

* The `data` field contains custom item attributes as JSON
* You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content
* The `sku` field is federated and can be used to resolve inventory item details from other services
* Each order item is linked to exactly one picking order via the `orderID` field

## Usage Example

### Basic Query

```graphql
query GetPickingOrderItems {
  pickingOrderItems(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      sku: "PROD-12345"
    }
  ) {
    edges {
      node {
        id
        sku
        quantity
        orderID
        data
        order {
          id
          customerID
          createdAt
        }
        createdAt
        updatedAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

### Query with JSON Field Filtering

```graphql
query FilterByCustomData {
  pickingOrderItems(
    first: 20,
    where: {
      DataHasKey: "priority",
      DataContains: ["priority", "high"]
    }
  ) {
    edges {
      node {
        id
        sku
        quantity
        data
      }
    }
    totalCount
  }
}
```

### JavaScript Example

```javascript
const getPickingOrderItemsQuery = `
  query GetPickingOrderItems($first: Int, $after: Cursor, $where: PickingOrderItemWhereInput) {
    pickingOrderItems(first: $first, after: $after, where: $where) {
      edges {
        node {
          id
          sku
          quantity
          orderID
          data
          order {
            id
            customerID
            createdAt
          }
          createdAt
          updatedAt
        }
        cursor
      }
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
      totalCount
    }
  }
`;

const variables = {
  first: 10,
  where: {
    sku: "PROD-12345"
  }
};

// Using fetch or your preferred GraphQL client
const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({
    query: getPickingOrderItemsQuery,
    variables: variables
  })
});

const result = await response.json();
console.log('Picking order items:', result.data.pickingOrderItems);

// Pagination example - fetching next page
if (result.data.pickingOrderItems.pageInfo.hasNextPage) {
  const nextPageVariables = {
    ...variables,
    after: result.data.pickingOrderItems.pageInfo.endCursor
  };
  // Make another request with nextPageVariables
}
```

## Related Queries

* [pickingOrders](/graphql-api/queries/pickingorders) - Query complete picking orders
* [nodePicking](/graphql-api/queries/nodepicking) - Retrieve specific picking objects by ID

## Related Mutations

* [createPickingOrderItem](/graphql-api/mutations/createpickingorderitem) - Create a new picking order item
* [updatePickingOrderItem](/graphql-api/mutations/updatepickingorderitem) - Update an existing picking order item
* [deletePickingOrderItem](/graphql-api/mutations/deletepickingorderitem) - Delete a picking order item


# Picking Orders

pickingOrders Query

Returns a paginated list of PickingOrder objects, with optional filtering and ordering.

## Arguments

| Name      | Type                     | Description                                                            |
| --------- | ------------------------ | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                 | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                    | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                 | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                    | Returns the last *n* elements from the list                            |
| `orderBy` | `PickingOrderOrder`      | Ordering options for PickingOrders returned from the connection        |
| `where`   | `PickingOrderWhereInput` | Filtering options for PickingOrders returned from the connection       |

## Return Type

`PickingOrderConnection!` - A connection to a list of PickingOrder objects with pagination information.

## Notes

The `data` field contains custom order attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](/graphql-api/advanced/json-field-queries).

To look up a key in `data` through a database index, for example a serial number across many orders, declare it as a data index and use the `dataIndex` filter: see [Data Indices](/graphql-api/advanced/data-indices). Its `contains` operator is a substring match; `DataContains` is not.

## Usage Example

```graphql
query {
  pickingOrders(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      customerID: "550e8400-e29b-41d4-a716-446655440000"
    }
  ) {
    edges {
      node {
        id
        customerID
        data
        orderitems {
          sku
          quantity
          item {
            data
          }
        }
        attachments {
          id
          filename
        }
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```


# Picking Outbound Shipment Notifications

pickingOutboundShipmentNotifications Query

Audience: Programmer

Returns a paginated list of `PickingOutboundShipmentNotification` objects, with optional filtering and ordering. Outbound shipment notifications allow downstream consumers to react when an outbound shipment (picking order) has completed.

## Arguments

| Name      | Type                                            | Description                                                                             |
| --------- | ----------------------------------------------- | --------------------------------------------------------------------------------------- |
| `after`   | `Cursor`                                        | Returns the elements in the list that come after the specified cursor                   |
| `first`   | `Int`                                           | Returns the first *n* elements from the list                                            |
| `before`  | `Cursor`                                        | Returns the elements in the list that come before the specified cursor                  |
| `last`    | `Int`                                           | Returns the last *n* elements from the list                                             |
| `orderBy` | `PickingOutboundShipmentNotificationOrder`      | Ordering options for PickingOutboundShipmentNotifications returned from the connection  |
| `where`   | `PickingOutboundShipmentNotificationWhereInput` | Filtering options for PickingOutboundShipmentNotifications returned from the connection |

## Return Type

`PickingOutboundShipmentNotificationConnection!` - A Relay connection to a list of `PickingOutboundShipmentNotification` objects with pagination information.

## Ordering Fields

The `PickingOutboundShipmentNotificationOrder` input supports ordering by the following fields:

| Field        | Description                          |
| ------------ | ------------------------------------ |
| `TENANT_ID`  | Order by tenant ID                   |
| `CREATED_AT` | Order by creation timestamp          |
| `CREATED_BY` | Order by creator user ID             |
| `UPDATED_AT` | Order by last update timestamp       |
| `UPDATED_BY` | Order by last updater user ID        |
| `DELETED_AT` | Order by deletion timestamp          |
| `DELETED_BY` | Order by deleter user ID             |
| `ORDER_ID`   | Order by the parent picking order ID |

The `PickingOutboundShipmentNotificationOrder` input also supports:

| Field       | Type                                            | Description                                                                                     |
| ----------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `direction` | `OrderDirection!`                               | Ordering direction (`ASC` or `DESC`, default `ASC`)                                             |
| `field`     | `PickingOutboundShipmentNotificationOrderField` | The field by which to order notifications                                                       |
| `jsonPath`  | `String`                                        | Dot-notation path into a JSONB column (e.g. `"meta.weight"`) used when ordering by a JSON field |
| `jsonType`  | `JSONType`                                      | Cast type for the extracted JSONB value                                                         |

## Notes

The `data` field contains custom notification attributes as JSON. The `PickingOutboundShipmentNotificationWhereInput` is extended with JSON-aware filters: `Data`, `DataHasKey`, `DataIn`, and `DataContains`. For complex JSON field queries, see [Advanced JSON Field Queries](/graphql-api/advanced/json-field-queries).

Soft-deleted notifications are excluded by default. Use `deletedAtNotNil: true` to include them when necessary.

## Usage Example

```graphql
query {
  pickingOutboundShipmentNotifications(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      orderID: "550e8400-e29b-41d4-a716-446655440000"
    }
  ) {
    edges {
      node {
        id
        tenantID
        dataTypeID
        dataTypeSlug
        data
        orderID
        order {
          id
          customerID
        }
        createdAt
        createdBy
        updatedAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    totalCount
  }
}
```

## Filtering by JSON Data

```graphql
query {
  pickingOutboundShipmentNotifications(
    first: 25,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      DataHasKey: "carrier",
      DataContains: ["carrier", "DHL"]
    }
  ) {
    edges {
      node {
        id
        orderID
        data
        createdAt
      }
    }
    totalCount
  }
}
```

## JavaScript Example

```javascript
const query = `
  query PickingOutboundShipmentNotifications(
    $first: Int,
    $orderBy: PickingOutboundShipmentNotificationOrder,
    $where: PickingOutboundShipmentNotificationWhereInput
  ) {
    pickingOutboundShipmentNotifications(first: $first, orderBy: $orderBy, where: $where) {
      edges {
        node {
          id
          orderID
          data
          createdAt
        }
      }
      totalCount
    }
  }
`;

const variables = {
  first: 10,
  orderBy: { direction: "DESC", field: "CREATED_AT" },
  where: { orderID: "550e8400-e29b-41d4-a716-446655440000" }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({ query, variables })
});

const result = await response.json();
console.log('Notifications:', result.data.pickingOutboundShipmentNotifications);
```


# Receiving Inbounds

receivingInbounds Query

Returns a paginated list of ReceivingInbound objects, with optional filtering and ordering.

## Arguments

| Name      | Type                         | Description                                                            |
| --------- | ---------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                     | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                        | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                     | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                        | Returns the last *n* elements from the list                            |
| `orderBy` | `ReceivingInboundOrder`      | Ordering options for ReceivingInbounds returned from the connection    |
| `where`   | `ReceivingInboundWhereInput` | Filtering options for ReceivingInbounds returned from the connection   |

## Return Type

`ReceivingInboundConnection!` - A connection to a list of ReceivingInbound objects with pagination information.

## Notes

The `data` field contains custom inbound attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  receivingInbounds(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      supplierID: "550e8400-e29b-41d4-a716-446655440000"
    }
  ) {
    edges {
      node {
        id
        orderID
        supplierID
        data
        inbounditems {
          sku
          quantity
        }
        attachments {
          id
          filename
        }
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```


# Receiving Inbound Items

receivingInboundItems Query

Audience: Programmers

Returns a paginated list of ReceivingInboundItem objects, with optional filtering and ordering. This query retrieves individual items that are part of receiving inbound shipments.

## Arguments

| Name      | Type                             | Description                                                              |
| --------- | -------------------------------- | ------------------------------------------------------------------------ |
| `after`   | `Cursor`                         | Returns the elements in the list that come after the specified cursor    |
| `first`   | `Int`                            | Returns the first *n* elements from the list                             |
| `before`  | `Cursor`                         | Returns the elements in the list that come before the specified cursor   |
| `last`    | `Int`                            | Returns the last *n* elements from the list                              |
| `orderBy` | `ReceivingInboundItemOrder`      | Ordering options for ReceivingInboundItems returned from the connection  |
| `where`   | `ReceivingInboundItemWhereInput` | Filtering options for ReceivingInboundItems returned from the connection |

## Return Type

`ReceivingInboundItemConnection!` - A connection to a list of [ReceivingInboundItem](/graphql-api/types/receivinginbounditem) objects with pagination information.

## Notes

* The `data` field contains custom inbound item attributes as JSON
* Use `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content
* Items are linked to their parent inbound shipment via `inboundID`
* Each item tracks its SKU and expected quantity
* Soft delete is supported through `deletedAt` and `deletedBy` fields

## Usage Examples

### Basic Query

```graphql
query {
  receivingInboundItems(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        sku
        quantity
        inboundID
        dataTypeSlug
        data
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

### Query Items by Inbound Shipment

```graphql
query {
  receivingInboundItems(
    where: {
      inboundID: "550e8400-e29b-41d4-a716-446655440000"
    }
  ) {
    edges {
      node {
        id
        sku
        quantity
        data
        inbound {
          id
          orderID
          supplierID
        }
      }
    }
    totalCount
  }
}
```

### Query Items by SKU

```graphql
query {
  receivingInboundItems(
    where: {
      skuContains: "PROD"
    },
    orderBy: { direction: ASC, field: SKU }
  ) {
    edges {
      node {
        id
        sku
        quantity
        inboundID
        dataTypeSlug
        createdAt
      }
    }
  }
}
```

### Query with Data Field Filtering

```graphql
query {
  receivingInboundItems(
    where: {
      DataHasKey: "lot_number",
      dataTypeSlug: "inbound_item"
    }
  ) {
    edges {
      node {
        id
        sku
        quantity
        data
        inbound {
          id
          supplierID
        }
      }
    }
  }
}
```

### JavaScript/TypeScript Example

```typescript
import { GraphQLClient } from 'graphql-request';

const client = new GraphQLClient('https://api.pyck.app/graphql', {
  headers: {
    authorization: `Bearer ${accessToken}`,
  },
});

const query = `
  query GetReceivingInboundItems($inboundID: ID!, $first: Int) {
    receivingInboundItems(
      where: { inboundID: $inboundID },
      first: $first,
      orderBy: { direction: ASC, field: SKU }
    ) {
      edges {
        node {
          id
          sku
          quantity
          dataTypeSlug
          data
          createdAt
          createdBy
        }
      }
      totalCount
    }
  }
`;

const variables = {
  inboundID: "550e8400-e29b-41d4-a716-446655440000",
  first: 20
};

const response = await client.request(query, variables);
console.log(`Found ${response.receivingInboundItems.totalCount} items`);
response.receivingInboundItems.edges.forEach(edge => {
  const item = edge.node;
  console.log(`SKU: ${item.sku}, Quantity: ${item.quantity}`);
  if (item.data) {
    console.log('Item data:', JSON.stringify(item.data, null, 2));
  }
});
```

## Ordering Options

The `ReceivingInboundItemOrderField` enum supports the following fields:

* `TENANT_ID`: Order by tenant identifier
* `CREATED_AT`: Order by creation timestamp
* `CREATED_BY`: Order by creator user ID
* `UPDATED_AT`: Order by last update timestamp
* `UPDATED_BY`: Order by last updater user ID
* `DELETED_AT`: Order by deletion timestamp
* `DELETED_BY`: Order by deleter user ID
* `SKU`: Order by stock keeping unit
* `INBOUND_ID`: Order by parent inbound shipment ID
* `QUANTITY`: Order by expected quantity

## Filtering Options

The `ReceivingInboundItemWhereInput` supports filtering by:

* All standard field predicates (equality, inequality, contains, etc.)
* `hasInbound`: Filter items that have an associated inbound
* `hasInboundWith`: Filter items based on properties of the parent inbound
* JSON data field queries using `Data`, `DataHasKey`, `DataIn`, and `DataContains`

## Related Types

* [ReceivingInboundItem](/graphql-api/types/receivinginbounditem) - The item type returned by this query
* [ReceivingInbound](/graphql-api/types/receivinginbound) - The parent inbound shipment type
* [PageInfo](/graphql-api/types/pageinfo) - Pagination information

## Service

This query is provided by the **Receiving** service, which manages all inbound shipment operations including item receiving, quality control, and put-away processes.


# Receiving Inbound Shipment Notifications

receivingInboundShipmentNotifications Query

Audience: Programmer

Returns a paginated list of `ReceivingInboundShipmentNotification` objects, with optional filtering and ordering. Inbound shipment notifications allow downstream consumers to react when an inbound receipt has completed.

## Arguments

| Name      | Type                                             | Description                                                                              |
| --------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------- |
| `after`   | `Cursor`                                         | Returns the elements in the list that come after the specified cursor                    |
| `first`   | `Int`                                            | Returns the first *n* elements from the list                                             |
| `before`  | `Cursor`                                         | Returns the elements in the list that come before the specified cursor                   |
| `last`    | `Int`                                            | Returns the last *n* elements from the list                                              |
| `orderBy` | `ReceivingInboundShipmentNotificationOrder`      | Ordering options for ReceivingInboundShipmentNotifications returned from the connection  |
| `where`   | `ReceivingInboundShipmentNotificationWhereInput` | Filtering options for ReceivingInboundShipmentNotifications returned from the connection |

## Return Type

`ReceivingInboundShipmentNotificationConnection!` - A Relay connection to a list of `ReceivingInboundShipmentNotification` objects with pagination information.

## Ordering Fields

The `ReceivingInboundShipmentNotificationOrder` input supports ordering by the following fields:

| Field        | Description                              |
| ------------ | ---------------------------------------- |
| `TENANT_ID`  | Order by tenant ID                       |
| `CREATED_AT` | Order by creation timestamp              |
| `CREATED_BY` | Order by creator user ID                 |
| `UPDATED_AT` | Order by last update timestamp           |
| `UPDATED_BY` | Order by last updater user ID            |
| `DELETED_AT` | Order by deletion timestamp              |
| `DELETED_BY` | Order by deleter user ID                 |
| `INBOUND_ID` | Order by the parent receiving inbound ID |

The `ReceivingInboundShipmentNotificationOrder` input also supports:

| Field       | Type                                             | Description                                                                                     |
| ----------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
| `direction` | `OrderDirection!`                                | Ordering direction (`ASC` or `DESC`, default `ASC`)                                             |
| `field`     | `ReceivingInboundShipmentNotificationOrderField` | The field by which to order notifications                                                       |
| `jsonPath`  | `String`                                         | Dot-notation path into a JSONB column (e.g. `"meta.weight"`) used when ordering by a JSON field |
| `jsonType`  | `JSONType`                                       | Cast type for the extracted JSONB value                                                         |

## Notes

The `data` field contains custom notification attributes as JSON. The `ReceivingInboundShipmentNotificationWhereInput` is extended with JSON-aware filters: `Data`, `DataHasKey`, `DataIn`, and `DataContains`. For complex JSON field queries, see [Advanced JSON Field Queries](/graphql-api/advanced/json-field-queries).

Soft-deleted notifications are excluded by default. Use `deletedAtNotNil: true` to include them when necessary.

## Usage Example

```graphql
query {
  receivingInboundShipmentNotifications(
    first: 10,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      inboundID: "550e8400-e29b-41d4-a716-446655440000"
    }
  ) {
    edges {
      node {
        id
        tenantID
        dataTypeID
        dataTypeSlug
        data
        inboundID
        inbound {
          id
          orderID
          supplierID
        }
        createdAt
        createdBy
        updatedAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    totalCount
  }
}
```

## Filtering by JSON Data

```graphql
query {
  receivingInboundShipmentNotifications(
    first: 25,
    orderBy: { direction: DESC, field: CREATED_AT },
    where: {
      DataHasKey: "carrier",
      DataContains: ["carrier", "DHL"]
    }
  ) {
    edges {
      node {
        id
        inboundID
        data
        createdAt
      }
    }
    totalCount
  }
}
```

## JavaScript Example

```javascript
const query = `
  query ReceivingInboundShipmentNotifications(
    $first: Int,
    $orderBy: ReceivingInboundShipmentNotificationOrder,
    $where: ReceivingInboundShipmentNotificationWhereInput
  ) {
    receivingInboundShipmentNotifications(first: $first, orderBy: $orderBy, where: $where) {
      edges {
        node {
          id
          inboundID
          data
          createdAt
        }
      }
      totalCount
    }
  }
`;

const variables = {
  first: 10,
  orderBy: { direction: "DESC", field: "CREATED_AT" },
  where: { inboundID: "550e8400-e29b-41d4-a716-446655440000" }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({ query, variables })
});

const result = await response.json();
console.log('Notifications:', result.data.receivingInboundShipmentNotifications);
```


# Repositories

Repositories Query

Returns a paginated list of Repository objects, with optional filtering and ordering.

## Arguments

| Name      | Type                   | Description                                                            |
| --------- | ---------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`               | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                  | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`               | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                  | Returns the last *n* elements from the list                            |
| `orderBy` | `RepositoryOrder`      | Ordering options for Repositories returned from the connection         |
| `where`   | `RepositoryWhereInput` | Filtering options for Repositories returned from the connection        |

## Return Type

`RepositoryConnection!` - A connection to a list of Repository objects with pagination information.

## Notes

The `data` field contains custom repository attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  repositories(
    first: 20,
    orderBy: { direction: ASC, field: NAME },
    where: {
      type: static,
      virtualRepo: false,
      or: [
        { nameContains: "North" },
        { nameContains: "South" }
      ]
    }
  ) {
    edges {
      node {
        id
        name
        type
        virtualRepo
        layout
        parentID
        data
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```


# Repository Movements

repositoryMovements Query

Returns a paginated list of RepositoryMovement objects, with optional filtering and ordering.

## Arguments

| Name      | Type                           | Description                                                            |
| --------- | ------------------------------ | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                       | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                          | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                       | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                          | Returns the last *n* elements from the list                            |
| `orderBy` | `RepositoryMovementOrder`      | Ordering options for RepositoryMovements returned from the connection  |
| `where`   | `RepositoryMovementWhereInput` | Filtering options for RepositoryMovements returned from the connection |

## Return Type

`RepositoryMovementConnection!` - A connection to a list of RepositoryMovement objects with pagination information.

## Notes

The `data` field contains custom movement attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  # Get pending repository movements
  repositoryMovements(
    where: { executed: false }
    orderBy: { field: CREATED_AT, direction: ASC }
    first: 10
  ) {
    edges {
      node {
        id
        repository {
          id
          name
          type
        }
        from {
          name
        }
        to {
          name
        }
        executed
        blockedBy
      }
    }
    totalCount
  }
}
```

```graphql
query {
  # Get movements for a specific repository
  repositoryMovements(
    where: { 
      repositoryID: "pallet-123",
      executedAt_GTE: "2024-01-01T00:00:00Z"
    }
  ) {
    edges {
      node {
        id
        executedAt
        from {
          name
        }
        to {
          name
        }
      }
    }
  }
}
```

## Common Filters

* `executed` - Filter by execution status
* `repositoryID` - Find movements for a specific repository
* `fromID` / `toID` - Filter by source or destination
* `blockedBy` - Find blocked movements
* `collectionID` - Find movements in a collection
* `executedAt_GTE` / `executedAt_LTE` - Filter by execution date range

## Notes

* Repository movements track the relocation of dynamic repositories
* Use this to monitor pallet movements, tote transfers, etc.
* Movements must be executed to take effect
* Can be part of collection movements for batch operations


# Stocks

Stocks Query

Returns a paginated list of Stock objects, with optional filtering and ordering.

## Arguments

| Name      | Type              | Description                                                            |
| --------- | ----------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`          | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`             | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`          | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`             | Returns the last *n* elements from the list                            |
| `orderBy` | `StockOrder`      | Ordering options for Stocks returned from the connection               |
| `where`   | `StockWhereInput` | Filtering options for Stocks returned from the connection              |

## Return Type

`StockConnection!` - A connection to a list of Stock objects with pagination information.

## Stock Fields

| Field              | Type            | Description                                  |
| ------------------ | --------------- | -------------------------------------------- |
| `id`               | `ID!`           | Unique identifier                            |
| `itemID`           | `UUID!`         | ID of the inventory item                     |
| `repositoryID`     | `UUID!`         | ID of the repository                         |
| `quantity`         | `Int!`          | Total quantity including child repositories  |
| `ownQuantity`      | `Int!`          | Quantity in this repository only             |
| `incomingStock`    | `Int!`          | Pending incoming movements                   |
| `ownIncomingStock` | `Int!`          | Incoming movements to this repository only   |
| `outgoingStock`    | `Int!`          | Pending outgoing movements                   |
| `ownOutgoingStock` | `Int!`          | Outgoing movements from this repository only |
| `item`             | `InventoryItem` | The inventory item details                   |
| `repository`       | `Repository`    | The repository details                       |

## Usage Example

```graphql
query {
  # Get all stock levels for a specific item across repositories
  stocks(
    where: {
      itemID: "item-123"
    }
  ) {
    edges {
      node {
        id
        itemID
        repositoryID
        quantity
        ownQuantity
        incomingStock
        outgoingStock
        item {
          sku
          data
        }
        repository {
          name
          type
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get all stock in a specific repository with quantities
  stocks(
    where: {
      repositoryID: "warehouse-main",
      quantity_LTE: 10,
      quantity_GT: 0
    },
    orderBy: { direction: ASC, field: QUANTITY }
  ) {
    edges {
      node {
        id
        itemID
        quantity
        ownQuantity
        incomingStock
        outgoingStock
        item {
          sku
          data
        }
      }
    }
    totalCount
  }
}
```

## Notes

* **Available Stock** can be calculated as: `quantity - outgoingStock`
* **Projected Stock** can be calculated as: `quantity + incomingStock - outgoingStock`
* The `quantity` field includes stock in all child repositories
* Use `ownQuantity` when you need stock at a specific location only
* Virtual repositories may have stock records but don't enforce validation


# Suppliers

suppliers Query

Returns a paginated list of Supplier objects, with optional filtering and ordering.

## Arguments

| Name      | Type                 | Description                                                            |
| --------- | -------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`             | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`             | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                | Returns the last *n* elements from the list                            |
| `orderBy` | `SupplierOrder`      | Ordering options for Suppliers returned from the connection            |
| `where`   | `SupplierWhereInput` | Filtering options for Suppliers returned from the connection           |

## Return Type

`SupplierConnection!` - A connection to a list of Supplier objects with pagination information.

## Usage Example

```graphql
query {
  # Find suppliers certified ISO9001 ("certifications": ["ISO9001", "ISO14001"])
  suppliers(
    where: {
      DataContains: ["certifications", "ISO9001"]
    },
    orderBy: { field: CREATED_AT, direction: DESC }
  ) {
    edges {
      node {
        id
        data
        dataTypeSlug
        createdAt
      }
    }
    totalCount
  }
}
```

```graphql
query {
  # Get suppliers by type
  suppliers(
    where: {
      dataTypeSlug: "international_supplier"
    },
    first: 20
  ) {
    edges {
      node {
        id
        data
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

## Common Filters

* `DataContains` - Value at the path contains the value: an array holds it as a string element, a string equals it exactly (case-sensitive)
* `DataHasKey` - Filter by presence of specific data keys
* `dataTypeSlug` - Filter by supplier type
* `createdAt_GTE` / `createdAt_LTE` - Filter by date range

For detailed information on querying JSON data fields, see the [Advanced JSON Field Queries](/graphql-api/advanced/json-field-queries) guide.

## Notes

* Suppliers are master data entities for vendor management
* Custom supplier attributes are stored in the `data` field
* Use data type slugs to categorize different supplier types


# Transactions

Transactions Query

Returns a paginated list of Transaction objects representing stock changes, with optional filtering and ordering.

## Arguments

| Name      | Type                    | Description                                                            |
| --------- | ----------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                   | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                   | Returns the last *n* elements from the list                            |
| `orderBy` | `TransactionOrder`      | Ordering options for transactions returned from the connection         |
| `where`   | `TransactionWhereInput` | Filtering options for transactions returned from the connection        |

## Return Type

`TransactionConnection!` - A connection to a list of Transaction objects with pagination information.

## Notes

The `data` field contains custom transaction attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  # Get all transactions for a specific repository today
  transactions(
    where: {
      repositoryID: "warehouse-main",
      createdAt_GTE: "2024-01-15T00:00:00Z",
      createdAt_LTE: "2024-01-15T23:59:59Z"
    },
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        quantity
        type
        createdAt
        item {
          sku
          data
        }
        repository {
          name
        }
        movement {
          id
          fromRepositoryID
          toRepositoryID
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get stock adjustments (non-movement transactions)
  transactions(
    where: {
      movementID_NULL: true,
      type: ADJUSTMENT
    },
    first: 20
  ) {
    edges {
      node {
        id
        quantity
        type
        data
        createdAt
        createdBy
        item {
          sku
        }
        repository {
          name
        }
      }
    }
  }
}
```

## Common Filters

* `itemID` - Filter by specific item
* `repositoryID` - Filter by specific repository
* `type` - Filter by transaction type
* `movementID_NULL: true` - Find manual adjustments
* `quantity_GT: 0` - Find incoming transactions
* `quantity_LT: 0` - Find outgoing transactions

## Notes

* Transactions are immutable audit records
* Every executed movement creates two transactions (outgoing and incoming)
* Manual adjustments create single transactions
* Use for audit trails and historical analysis


# Users

Users Query

Returns a paginated list of User objects, with optional filtering and ordering. Users represent people who can access and interact with the pyck system.

## Arguments

| Name      | Type             | Description                                                            |
| --------- | ---------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`         | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`            | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`         | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`            | Returns the last *n* elements from the list                            |
| `orderBy` | `UserOrder`      | Ordering options for users returned from the connection                |
| `where`   | `UserWhereInput` | Filtering options for users returned from the connection               |

## Return Type

`UserConnection!` - A connection to a list of User objects with pagination information.

## Usage Example

```graphql
query {
  # Search users by email domain
  users(
    where: {
      emailContains: "@company.com"
    },
    orderBy: { direction: ASC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        username
        email
        firstName
        lastName
        isAdmin
        tenantID
        company {
          id
          name
        }
        roles {
          id
          name
        }
        groups {
          id
          name
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Get admin users
  users(
    where: {
      isAdmin: true
    },
    first: 20
  ) {
    edges {
      node {
        id
        username
        email
        firstName
        lastName
        createdAt
        roles {
          id
          name
          description
        }
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

```graphql
query {
  # Find users by name and company
  users(
    where: {
      firstNameContains: "John",
      hasCompanyWith: [
        { nameContains: "Tech" }
      ]
    }
  ) {
    edges {
      node {
        id
        username
        email
        firstName
        lastName
        company {
          id
          name
          organizationID
        }
        roles {
          name
        }
      }
    }
  }
}
```

## Common Filters

* `usernameContains` - Search by username substring
* `username` - Find by exact username
* `emailContains` - Search by email substring
* `email` - Find by exact email address
* `firstNameContains` / `lastNameContains` - Search by name
* `isAdmin` - Filter by admin status
* `tenantID` - Filter by tenant
* `hasCompany` - Filter users who have a company
* `hasCompanyWith` - Filter by company criteria
* `hasRoles` - Filter users who have roles
* `hasRolesWith` - Filter by role criteria

## Notes

* Users are authenticated through an Identity Provider (IDP)
* Each user belongs to a tenant for multi-tenancy support
* Users can be associated with a company within their tenant
* Role-based access control through roles and groups
* Legacy roles field is deprecated in favor of role relations
* Admin users have elevated privileges across the system
* Integration with external authentication systems via idpID field


# AssignableWorkflowExecutions

Query workflow executions that have pending user tasks

Audience: Programmer

Returns a paginated list of Temporal workflow executions that have pending user tasks. Unlike `workflowExecutions`, this query filters results to only include workflows where the `ActivityCount` in `UserDataInput` is greater than zero. Workflows that do not have user task handlers or have no pending activities are excluded from the results.

This query is designed for client applications that need to present a list of workflows awaiting user action, such as a task inbox or assignment queue, without requiring the client to fetch all executions and filter locally.

The query uses the same pagination interface, filtering options, and return types as `workflowExecutions`.

## Service

Owned by the **Workflow** service.

## Arguments

| Name      | Type                           | Description                                             |
| --------- | ------------------------------ | ------------------------------------------------------- |
| `where`   | `WorkflowExecutionsWhereInput` | Filter criteria for workflow executions                 |
| `first`   | `Int`                          | Maximum number of executions to return. Defaults to 100 |
| `after`   | `String`                       | Pagination cursor from previous response                |
| `orderBy` | `WorkflowExecutionOrder`       | Ordering options for the returned list                  |

## Return Type

`WorkflowExecutionInfoConnection!` - A connection containing workflow execution information with pagination support.

### Connection Fields

| Field        | Type                            | Description                                                          |
| ------------ | ------------------------------- | -------------------------------------------------------------------- |
| `edges`      | `[WorkflowExecutionInfoEdge!]!` | List of workflow execution edges                                     |
| `pageInfo`   | `WorkflowExecutionPageInfo!`    | Pagination information                                               |
| `totalCount` | `Int!`                          | Total count of all assignable executions (not just the current page) |

### Edge Fields

| Field    | Type                     | Description                        |
| -------- | ------------------------ | ---------------------------------- |
| `node`   | `WorkflowExecutionInfo!` | The workflow execution information |
| `cursor` | `String!`                | Cursor for pagination              |

## Filter Options (WorkflowExecutionsWhereInput)

The `where` parameter accepts the same `WorkflowExecutionsWhereInput` as the `workflowExecutions` query, including support for logical operators (`or`, `and`, `not`) and advanced string predicates (`hasPrefix`, `hasSuffix`, `equalFold`, `containsFold`).

For complete documentation of all available filters, see [workflowExecutions](/graphql-api/queries/workflowexecutions#filter-options-workflowexecutionswhereinput).

Common filters include:

### Workflow Identification

| Filter                | Type        | Description                            |
| --------------------- | ----------- | -------------------------------------- |
| `workflowID`          | `String`    | Exact workflow ID match                |
| `workflowIDIn`        | `[String!]` | Match any of the provided workflow IDs |
| `workflowIDHasPrefix` | `String`    | Workflow ID starts with                |
| `workflowIDContains`  | `String`    | Workflow ID contains substring         |
| `runID`               | `String`    | Exact run ID match                     |
| `runIDIn`             | `[String!]` | Match any of the provided run IDs      |

### Workflow Type

| Filter              | Type        | Description                          |
| ------------------- | ----------- | ------------------------------------ |
| `typeName`          | `String`    | Exact workflow type name             |
| `typeNameIn`        | `[String!]` | Match any of the provided type names |
| `typeNameContains`  | `String`    | Type name contains substring         |
| `typeNameHasPrefix` | `String`    | Type name starts with                |

### Status

| Filter        | Type        | Description                                           |
| ------------- | ----------- | ----------------------------------------------------- |
| `status`      | `String`    | Exact status match (RUNNING, COMPLETED, FAILED, etc.) |
| `statusIn`    | `[String!]` | Match any of the provided statuses                    |
| `statusNotIn` | `[String!]` | Exclude specific statuses                             |

### Time Filters

| Filter            | Type      | Description                    |
| ----------------- | --------- | ------------------------------ |
| `startTime`       | `String`  | Exact start time (ISO 8601)    |
| `startTimeGT`     | `String`  | Started after                  |
| `startTimeGTE`    | `String`  | Started at or after            |
| `startTimeLT`     | `String`  | Started before                 |
| `startTimeLTE`    | `String`  | Started at or before           |
| `closeTime`       | `String`  | Exact close time               |
| `closeTimeIsNil`  | `Boolean` | Still running (no close time)  |
| `closeTimeNotNil` | `Boolean` | Has completed (has close time) |

### Search Attributes

| Filter       | Type        | Description                   |
| ------------ | ----------- | ----------------------------- |
| `service`    | `String`    | Service name search attribute |
| `serviceIn`  | `[String!]` | Match any of the services     |
| `dataType`   | `String`    | Data type search attribute    |
| `dataTypeIn` | `[String!]` | Match any data types          |
| `dataId`     | `String`    | Data ID search attribute      |
| `dataIdIn`   | `[String!]` | Match any data IDs            |

### Assignment

| Filter           | Type        | Description          |
| ---------------- | ----------- | -------------------- |
| `assignee`       | `String`    | Exact assignee match |
| `assigneeIn`     | `[String!]` | Match any assignees  |
| `assigneeIsNil`  | `Boolean`   | Unassigned workflows |
| `assigneeNotNil` | `Boolean`   | Assigned workflows   |
| `groupBy`        | `String`    | Group by value       |

### Title and Group Title (pyck\_title / pyck\_group\_title search attributes)

| Filter                | Type        | Description                                                   |
| --------------------- | ----------- | ------------------------------------------------------------- |
| `title`               | `String`    | Exact match against `pyck_title` (per-workflow display label) |
| `titleIn`             | `[String!]` | Match any of the provided titles                              |
| `titleHasPrefix`      | `String`    | Title starts with                                             |
| `titleContainsFold`   | `String`    | Case-insensitive substring match                              |
| `titleIsNil`          | `Boolean`   | Title not set (matches missing attribute or empty string)     |
| `groupTitle`          | `String`    | Exact match against `pyck_group_title` (group header label)   |
| `groupTitleIn`        | `[String!]` | Match any of the provided group titles                        |
| `groupTitleHasPrefix` | `String`    | Group title starts with                                       |
| `groupTitleIsNil`     | `Boolean`   | Group title not set                                           |

See the [workflowExecutions filter reference](/graphql-api/queries/workflowexecutions#title-pyck_title-search-attribute) for the full list of title and group title predicates (NEQ, NotIn, Contains, HasSuffix, EqualFold, ContainsFold, NotNil).

### Logical Operators

| Filter | Type                              | Description               |
| ------ | --------------------------------- | ------------------------- |
| `and`  | `[WorkflowExecutionsWhereInput!]` | All conditions must match |
| `or`   | `[WorkflowExecutionsWhereInput!]` | Any condition matches     |
| `not`  | `WorkflowExecutionsWhereInput`    | Negate condition          |

## Ordering Options (WorkflowExecutionOrder)

| Field       | Values                                                                      | Description                                 |
| ----------- | --------------------------------------------------------------------------- | ------------------------------------------- |
| `direction` | `ASC`, `DESC`                                                               | Sort direction (defaults to `DESC`)         |
| `field`     | `START_TIME`, `CLOSE_TIME`, `WORKFLOW_ID`, `STATUS`, `TITLE`, `GROUP_TITLE` | Field to sort by (defaults to `START_TIME`) |

`TITLE` orders alphabetically by the `pyck_title` search attribute; `GROUP_TITLE` orders by the `pyck_group_title` search attribute.

## Usage Examples

### List All Assignable Workflows

```graphql
query {
  assignableWorkflowExecutions(
    first: 50
    orderBy: { direction: DESC, field: START_TIME }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        searchAttributes {
          key
          value
        }
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

### Filter by Workflow Type

Retrieve assignable workflows for a specific workflow type, for example only picking-related workflows awaiting user action.

```graphql
query {
  assignableWorkflowExecutions(
    where: {
      typeName: "PickingWorkflow"
    }
    first: 25
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        searchAttributes {
          key
          value
        }
        taskQueue
      }
    }
    totalCount
  }
}
```

### Filter Unassigned Workflows Awaiting Action

Find workflows that have pending user tasks but are not yet assigned to anyone.

```graphql
query {
  assignableWorkflowExecutions(
    where: {
      assigneeIsNil: true
      status: "RUNNING"
    }
    first: 100
    orderBy: { direction: ASC, field: START_TIME }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        searchAttributes {
          key
          value
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

### Filter by Service and Data Type

List assignable workflows belonging to a specific service and data type.

```graphql
query {
  assignableWorkflowExecutions(
    where: {
      service: "picking"
      dataType: "picking-order"
    }
    first: 50
  ) {
    edges {
      node {
        execution {
          workflowId
        }
        status
        searchAttributes {
          key
          value
        }
      }
    }
    totalCount
  }
}
```

### Paginating Through Results

```graphql
# First page
query FirstPage {
  assignableWorkflowExecutions(
    where: { status: "RUNNING" }
    first: 25
  ) {
    edges {
      node {
        execution { workflowId }
        type { name }
        status
        searchAttributes { key value }
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

# Next page (use endCursor from previous response)
query NextPage {
  assignableWorkflowExecutions(
    where: { status: "RUNNING" }
    first: 25
    after: "YXNzaWduYWJsZV9vZmZzZXQ6MjU="
  ) {
    edges {
      node {
        execution { workflowId }
        type { name }
        status
        searchAttributes { key value }
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

## Example Response

```json
{
  "data": {
    "assignableWorkflowExecutions": {
      "edges": [
        {
          "node": {
            "execution": {
              "workflowId": "picking-order-12345",
              "id": "run-abc-123"
            },
            "type": {
              "name": "PickingWorkflow"
            },
            "status": "RUNNING",
            "startTime": "2024-01-15T10:30:00Z",
            "closeTime": null,
            "searchAttributes": [
              { "key": "pyck_title", "value": "Picking Order #12345" },
              { "key": "pyck_group_title", "value": "Zone A" }
            ]
          },
          "cursor": "YXNzaWduYWJsZV9vZmZzZXQ6MQ=="
        },
        {
          "node": {
            "execution": {
              "workflowId": "receiving-inbound-67890",
              "id": "run-def-456"
            },
            "type": {
              "name": "ReceivingWorkflow"
            },
            "status": "RUNNING",
            "startTime": "2024-01-15T09:15:00Z",
            "closeTime": null,
            "searchAttributes": [
              { "key": "pyck_title", "value": "Receiving Inbound #67890" },
              { "key": "pyck_group_title", "value": "Dock B" }
            ]
          },
          "cursor": "YXNzaWduYWJsZV9vZmZzZXQ6Mg=="
        }
      ],
      "pageInfo": {
        "hasNextPage": true,
        "endCursor": "YXNzaWduYWJsZV9vZmZzZXQ6Mg=="
      },
      "totalCount": 47
    }
  }
}
```

## Comparison with workflowExecutions

| Feature                           | `workflowExecutions`                 | `assignableWorkflowExecutions`       |
| --------------------------------- | ------------------------------------ | ------------------------------------ |
| Returns all executions            | Yes                                  | No                                   |
| Filters by user task availability | No                                   | Yes (ActivityCount > 0)              |
| Arguments                         | `where`, `first`, `after`, `orderBy` | `where`, `first`, `after`, `orderBy` |
| Return type                       | `WorkflowExecutionInfoConnection!`   | `WorkflowExecutionInfoConnection!`   |
| Pagination support                | Yes                                  | Yes                                  |

## Performance Considerations

* This query fetches all pages from Temporal upfront to compute an accurate `totalCount`, then paginates the results in-memory using offset-based cursors.
* For single-tenant requests, all matching workflows are retrieved from Temporal first, filtered for assignability, and then paginated.
* For multi-tenant requests, all matching executions are fetched first, then filtered concurrently across tenants.
* Because all results must be fetched to determine the total count, this query may have higher latency for large result sets compared to simple cursor-based pagination.
* Use filtering parameters such as `typeName`, `status`, or `service` to narrow results and improve performance.
* The default page size is 100 if `first` is not specified.

## Important Changes

{% hint style="info" %}
**Pagination Fix (March 2026)**: The pagination implementation was updated to fix two critical bugs:

1. `totalCount` now returns the total number of assignable workflows across all pages (previously returned only the current page count)
2. Cursor format changed from `workflowId:runId` to opaque offset-based cursors for consistent pagination

If you have existing client code that parses cursor values, you must update it to treat cursors as opaque strings.
{% endhint %}

## Notes

* Only workflows with `ActivityCount > 0` in their `UserDataInput` are returned. This means the workflow must have registered user task handlers and have at least one pending activity.
* Workflows without user task handlers or where all activities have been completed will not appear in the results.
* The query shares the same return type (`WorkflowExecutionInfoConnection`) as `workflowExecutions`, so client code can be reused across both queries.
* Cursor values are opaque offset-based strings (base64-encoded). Do not attempt to parse or construct cursors manually; always use the `endCursor` value from the `pageInfo` response.
* **Logical operators** (`or`, `and`, `not`) are fully supported for building complex filter conditions.
* **String predicates** include both case-sensitive and case-insensitive variants for flexible searching.

## Related Documentation

* [workflowExecutions](/graphql-api/queries/workflowexecutions) - Query all workflow executions
* [workflowHistory](/graphql-api/queries/workflowhistory) - Fetch workflow history events
* [workflowAssignee](/graphql-api/queries/workflowassignee) - Retrieve workflow assignee
* [WorkflowExecutionInfo](/graphql-api/types/workflowexecutioninfo) - Execution info type
* [WorkflowExecutionInfoConnection](/graphql-api/types/workflowexecutioninfoconnection) - Connection type


# Workflows

Workflows Query

Returns a paginated list of Workflow objects, with optional filtering and ordering. Workflows represent business process definitions that can be executed by the Temporal workflow engine.

## Arguments

| Name      | Type                 | Description                                                            |
| --------- | -------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`             | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`             | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                | Returns the last *n* elements from the list                            |
| `orderBy` | `WorkflowOrder`      | Ordering options for workflows returned from the connection            |
| `where`   | `WorkflowWhereInput` | Filtering options for workflows returned from the connection           |

## Return Type

`WorkflowConnection!` - A connection to a list of Workflow objects with pagination information.

## Notes

The `data` field contains custom workflow attributes as JSON. You can use the `Data`, `DataHasKey`, `DataIn`, and `DataContains` filters to query based on JSON content. For complex JSON field queries, see [Advanced JSON Field Queries](https://github.com/pyck-ai/docs/blob/main/graphql/advanced/json-field-queries.md).

## Usage Example

```graphql
query {
  # Get active workflows
  workflows(
    where: {
      active: true
    },
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        name
        active
        filterRule
        dataTypeSlug
        data
        createdAt
        workflowsignals {
          id
          eventName
          start
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Search workflows by name
  workflows(
    where: {
      nameContains: "picking"
    },
    first: 20
  ) {
    edges {
      node {
        id
        name
        active
        filterRule
        dataTypeSlug
        data
        workflowsignals {
          id
          eventName
          start
          data
        }
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

```graphql
query {
  # Get workflows with specific data type
  workflows(
    where: {
      dataTypeSlug: "order_processing"
    }
  ) {
    edges {
      node {
        id
        name
        active
        filterRule
        data
        workflowsignals {
          id
          eventName
          start
          createdAt
        }
      }
    }
  }
}
```

## Common Filters

* `nameContains` - Search by workflow name substring
* `name` - Find by exact workflow name
* `active` - Filter by active status
* `dataTypeSlug` - Filter by data type slug
* `filterRule` - Filter by rule definition
* `tenantID` - Filter by tenant
* `createdAtGTE` / `createdAtLTE` - Filter by creation date range

## Notes

* Workflows define business process templates for execution
* Integration with Temporal.io workflow engine for reliable execution
* Active workflows are available for execution
* Filter rules determine when workflows should be triggered
* Workflow signals define the events that can start or control workflows
* Support custom fields through data/dataType system
* Essential for orchestrating complex business operations across services


# WorkflowAssignee

Retrieve the assignee of a specific workflow run

Audience: Programmer

Retrieves the assignee for a specific workflow run. This query fetches the assignee information from the workflow's search attributes in the Temporal workflow engine, providing visibility into who is responsible for a particular workflow execution.

## Arguments

| Name    | Type                | Description                                      |
| ------- | ------------------- | ------------------------------------------------ |
| `input` | `GetAssigneeInput!` | Input containing workflow identifiers (required) |

### GetAssigneeInput Fields

| Field           | Type      | Description                                   |
| --------------- | --------- | --------------------------------------------- |
| `workflowID`    | `String!` | The unique identifier of the workflow         |
| `workflowRunID` | `String!` | The specific run ID of the workflow execution |

## Return Type

`GetAssigneeResponse!` - Response containing the assignee information (non-nullable)

### GetAssigneeResponse Fields

| Field      | Type      | Description                                      |
| ---------- | --------- | ------------------------------------------------ |
| `assignee` | `String!` | The ID of the user assigned to this workflow run |

## Usage Example

### GraphQL Query

```graphql
query GetWorkflowAssignee {
  workflowAssignee(input: {
    workflowID: "order-processing-workflow-123"
    workflowRunID: "run-456-xyz"
  }) {
    assignee
  }
}
```

### JavaScript Example

```javascript
const query = `
  query GetWorkflowAssignee($input: GetAssigneeInput!) {
    workflowAssignee(input: $input) {
      assignee
    }
  }
`;

const variables = {
  input: {
    workflowID: "order-processing-workflow-123",
    workflowRunID: "run-456-xyz"
  }
};

// Using fetch API
const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    query,
    variables
  })
});

const result = await response.json();
console.log('Assignee:', result.data.workflowAssignee.assignee);
```

## Response Example

```json
{
  "data": {
    "workflowAssignee": {
      "assignee": "user-12345"
    }
  }
}
```

## Error Handling

The query may return errors in the following cases:

### Invalid WorkflowID

```json
{
  "errors": [{
    "message": "invalid WorkflowID",
    "path": ["workflowAssignee"]
  }]
}
```

### Invalid WorkflowRunID

```json
{
  "errors": [{
    "message": "invalid WorkflowRunID",
    "path": ["workflowAssignee"]
  }]
}
```

### Workflow Not Found

```json
{
  "errors": [{
    "message": "workflow not found: order-processing-workflow-123",
    "path": ["workflowAssignee"]
  }]
}
```

### Invalid Workflow Client

```json
{
  "errors": [{
    "message": "invalid workflowClient",
    "path": ["workflowAssignee"]
  }]
}
```

## Notes

* The assignee is stored in the workflow's search attributes under the key `pyck_workflow_assignee`
* If no assignee is set for the workflow, the query returns an empty string
* Requires valid authentication and appropriate tenant context
* The workflow must exist in the Temporal workflow engine for the query to succeed
* This query is useful for tracking responsibility and routing work items in workflow-driven processes
* The assignee ID typically corresponds to a user in the system's identity management (Zitadel)

## Related Types

* [GetAssigneeInput](/graphql-api/inputs/getassigneeinput)
* [GetAssigneeResponse](/graphql-api/types/getassigneeresponse)

## Related Mutations

* `setWorkflowAssignee` - Set or update the assignee for a workflow run

## Service

This query is provided by the **workflow** service as part of the federated GraphQL schema.


# WorkflowExecutions

Query workflow executions with pagination and filtering

Audience: Programmer

Returns a paginated list of Temporal workflow executions with optional filtering and ordering. This query provides lightweight execution metadata without history for efficient retrieval of workflow execution status.

For workflow history events, use the separate `workflowHistory` query.

## Arguments

| Name      | Type                           | Description                                                            |
| --------- | ------------------------------ | ---------------------------------------------------------------------- |
| `where`   | `WorkflowExecutionsWhereInput` | Filter criteria for workflow executions                                |
| `first`   | `Int`                          | Maximum number of executions to return. Defaults to 100                |
| `after`   | `String`                       | Pagination cursor from previous response (NextPageToken from Temporal) |
| `orderBy` | `WorkflowExecutionOrder`       | Ordering options for the returned list                                 |

## Return Type

`WorkflowExecutionInfoConnection!` - A connection containing workflow execution information with pagination support.

### Connection Fields

| Field        | Type                            | Description                        |
| ------------ | ------------------------------- | ---------------------------------- |
| `edges`      | `[WorkflowExecutionInfoEdge!]!` | List of workflow execution edges   |
| `pageInfo`   | `WorkflowExecutionPageInfo!`    | Pagination information             |
| `totalCount` | `Int!`                          | Total count of matching executions |

### Edge Fields

| Field    | Type                     | Description                        |
| -------- | ------------------------ | ---------------------------------- |
| `node`   | `WorkflowExecutionInfo!` | The workflow execution information |
| `cursor` | `String!`                | Cursor for pagination              |

## Filter Options (WorkflowExecutionsWhereInput)

### Workflow Identification

| Filter                   | Type        | Description                                     |
| ------------------------ | ----------- | ----------------------------------------------- |
| `workflowID`             | `String`    | Exact workflow ID match                         |
| `workflowIDNeq`          | `String`    | Not equal to workflow ID                        |
| `workflowIDIn`           | `[String!]` | Match any of the provided workflow IDs          |
| `workflowIDNotIn`        | `[String!]` | Exclude specific workflow IDs                   |
| `workflowIDHasPrefix`    | `String`    | Workflow ID starts with                         |
| `workflowIDHasSuffix`    | `String`    | Workflow ID ends with                           |
| `workflowIDContains`     | `String`    | Workflow ID contains substring (case-sensitive) |
| `workflowIDEqualFold`    | `String`    | Case-insensitive equality match                 |
| `workflowIDContainsFold` | `String`    | Case-insensitive substring match                |
| `runID`                  | `String`    | Exact run ID match                              |
| `runIDNeq`               | `String`    | Not equal to run ID                             |
| `runIDIn`                | `[String!]` | Match any of the provided run IDs               |
| `runIDNotIn`             | `[String!]` | Exclude specific run IDs                        |
| `runIDHasPrefix`         | `String`    | Run ID starts with                              |
| `runIDHasSuffix`         | `String`    | Run ID ends with                                |
| `runIDContains`          | `String`    | Run ID contains substring (case-sensitive)      |
| `runIDEqualFold`         | `String`    | Case-insensitive equality match                 |
| `runIDContainsFold`      | `String`    | Case-insensitive substring match                |

### Workflow Type

| Filter                 | Type        | Description                                   |
| ---------------------- | ----------- | --------------------------------------------- |
| `typeName`             | `String`    | Exact workflow type name                      |
| `typeNameNeq`          | `String`    | Not equal to type name                        |
| `typeNameIn`           | `[String!]` | Match any of the provided type names          |
| `typeNameNotIn`        | `[String!]` | Exclude specific type names                   |
| `typeNameHasPrefix`    | `String`    | Type name starts with                         |
| `typeNameHasSuffix`    | `String`    | Type name ends with                           |
| `typeNameContains`     | `String`    | Type name contains substring (case-sensitive) |
| `typeNameEqualFold`    | `String`    | Case-insensitive equality match               |
| `typeNameContainsFold` | `String`    | Case-insensitive substring match              |

### Workflow Name

| Filter                     | Type        | Description                                         |
| -------------------------- | ----------- | --------------------------------------------------- |
| `workflowName`             | `String`    | Exact workflow name match (custom search attribute) |
| `workflowNameNeq`          | `String`    | Not equal to workflow name                          |
| `workflowNameIn`           | `[String!]` | Match any of the provided workflow names            |
| `workflowNameNotIn`        | `[String!]` | Exclude specific workflow names                     |
| `workflowNameHasPrefix`    | `String`    | Workflow name starts with                           |
| `workflowNameHasSuffix`    | `String`    | Workflow name ends with                             |
| `workflowNameContains`     | `String`    | Workflow name contains substring (case-sensitive)   |
| `workflowNameEqualFold`    | `String`    | Case-insensitive equality match                     |
| `workflowNameContainsFold` | `String`    | Case-insensitive substring match                    |

### Status

| Filter               | Type        | Description                                           |
| -------------------- | ----------- | ----------------------------------------------------- |
| `status`             | `String`    | Exact status match (RUNNING, COMPLETED, FAILED, etc.) |
| `statusNeq`          | `String`    | Not equal to status                                   |
| `statusIn`           | `[String!]` | Match any of the provided statuses                    |
| `statusNotIn`        | `[String!]` | Exclude specific statuses                             |
| `statusHasPrefix`    | `String`    | Status starts with                                    |
| `statusHasSuffix`    | `String`    | Status ends with                                      |
| `statusContains`     | `String`    | Status contains substring (case-sensitive)            |
| `statusEqualFold`    | `String`    | Case-insensitive equality match                       |
| `statusContainsFold` | `String`    | Case-insensitive substring match                      |

### Time Filters

| Filter            | Type      | Description                    |
| ----------------- | --------- | ------------------------------ |
| `startTime`       | `String`  | Exact start time (ISO 8601)    |
| `startTimeGT`     | `String`  | Started after                  |
| `startTimeGTE`    | `String`  | Started at or after            |
| `startTimeLT`     | `String`  | Started before                 |
| `startTimeLTE`    | `String`  | Started at or before           |
| `closeTime`       | `String`  | Exact close time               |
| `closeTimeGT`     | `String`  | Closed after                   |
| `closeTimeGTE`    | `String`  | Closed at or after             |
| `closeTimeIsNil`  | `Boolean` | Still running (no close time)  |
| `closeTimeNotNil` | `Boolean` | Has completed (has close time) |

### Search Attributes

| Filter                 | Type        | Description                                   |
| ---------------------- | ----------- | --------------------------------------------- |
| `service`              | `String`    | Exact service name match                      |
| `serviceNeq`           | `String`    | Not equal to service                          |
| `serviceIn`            | `[String!]` | Match any of the services                     |
| `serviceNotIn`         | `[String!]` | Exclude specific services                     |
| `serviceHasPrefix`     | `String`    | Service starts with                           |
| `serviceHasSuffix`     | `String`    | Service ends with                             |
| `serviceContains`      | `String`    | Service contains substring (case-sensitive)   |
| `serviceEqualFold`     | `String`    | Case-insensitive equality match               |
| `serviceContainsFold`  | `String`    | Case-insensitive substring match              |
| `serviceIsNil`         | `Boolean`   | Service is not set                            |
| `serviceNotNil`        | `Boolean`   | Service is set                                |
| `dataType`             | `String`    | Exact data type match                         |
| `dataTypeNeq`          | `String`    | Not equal to data type                        |
| `dataTypeIn`           | `[String!]` | Match any data types                          |
| `dataTypeNotIn`        | `[String!]` | Exclude specific data types                   |
| `dataTypeHasPrefix`    | `String`    | Data type starts with                         |
| `dataTypeHasSuffix`    | `String`    | Data type ends with                           |
| `dataTypeContains`     | `String`    | Data type contains substring (case-sensitive) |
| `dataTypeEqualFold`    | `String`    | Case-insensitive equality match               |
| `dataTypeContainsFold` | `String`    | Case-insensitive substring match              |
| `dataTypeIsNil`        | `Boolean`   | Data type is not set                          |
| `dataTypeNotNil`       | `Boolean`   | Data type is set                              |
| `dataId`               | `String`    | Exact data ID match                           |
| `dataIdNeq`            | `String`    | Not equal to data ID                          |
| `dataIdIn`             | `[String!]` | Match any data IDs                            |
| `dataIdNotIn`          | `[String!]` | Exclude specific data IDs                     |
| `dataIdHasPrefix`      | `String`    | Data ID starts with                           |
| `dataIdHasSuffix`      | `String`    | Data ID ends with                             |
| `dataIdContains`       | `String`    | Data ID contains substring                    |
| `dataIdIsNil`          | `Boolean`   | Data ID is not set                            |
| `dataIdNotNil`         | `Boolean`   | Data ID is set                                |

### Targets (KeywordList)

The `targets` and `targetsNotIn` predicates filter against the `pyck_workflow_targets` KeywordList search attribute. KeywordList semantics mean that a workflow matches when its declared target list contains **any** element of the supplied set; `targetsNotIn` excludes such matches.

| Filter         | Type                | Description                                                        |
| -------------- | ------------------- | ------------------------------------------------------------------ |
| `targets`      | `[WorkflowTarget!]` | Match workflows whose targets include any of the supplied values   |
| `targetsNotIn` | `[WorkflowTarget!]` | Exclude workflows whose targets include any of the supplied values |

See the [WorkflowTarget](/graphql-api/enums/workflowtarget) enum for the available values (`WEB`, `MOBILE`, `SETUP`).

### Assignment

| Filter                 | Type        | Description                                  |
| ---------------------- | ----------- | -------------------------------------------- |
| `assignee`             | `String`    | Exact assignee match                         |
| `assigneeNeq`          | `String`    | Not equal to assignee                        |
| `assigneeIn`           | `[String!]` | Match any assignees                          |
| `assigneeNotIn`        | `[String!]` | Exclude specific assignees                   |
| `assigneeHasPrefix`    | `String`    | Assignee starts with                         |
| `assigneeHasSuffix`    | `String`    | Assignee ends with                           |
| `assigneeContains`     | `String`    | Assignee contains substring (case-sensitive) |
| `assigneeEqualFold`    | `String`    | Case-insensitive equality match              |
| `assigneeContainsFold` | `String`    | Case-insensitive substring match             |
| `assigneeIsNil`        | `Boolean`   | Unassigned workflows                         |
| `assigneeNotNil`       | `Boolean`   | Assigned workflows                           |
| `groupBy`              | `String`    | Exact group by value                         |
| `groupByNeq`           | `String`    | Not equal to group by value                  |
| `groupByIn`            | `[String!]` | Match any group by values                    |
| `groupByNotIn`         | `[String!]` | Exclude specific group by values             |
| `groupByHasPrefix`     | `String`    | Group by starts with                         |
| `groupByHasSuffix`     | `String`    | Group by ends with                           |
| `groupByContains`      | `String`    | Group by contains substring (case-sensitive) |
| `groupByEqualFold`     | `String`    | Case-insensitive equality match              |
| `groupByContainsFold`  | `String`    | Case-insensitive substring match             |
| `groupByIsNil`         | `Boolean`   | Group by is not set                          |
| `groupByNotNil`        | `Boolean`   | Group by is set                              |

### Title (pyck\_title search attribute)

These predicates match the `pyck_title` Temporal search attribute, which holds the per-workflow display label written via `workflowsdk.SetWorkflowTitle`.

| Filter              | Type        | Description                                        |
| ------------------- | ----------- | -------------------------------------------------- |
| `title`             | `String`    | Exact title match                                  |
| `titleNEQ`          | `String`    | Not equal to title                                 |
| `titleIn`           | `[String!]` | Match any of the provided titles                   |
| `titleNotIn`        | `[String!]` | Exclude specific titles                            |
| `titleContains`     | `String`    | Title contains substring (case-sensitive)          |
| `titleHasPrefix`    | `String`    | Title starts with                                  |
| `titleHasSuffix`    | `String`    | Title ends with                                    |
| `titleEqualFold`    | `String`    | Case-insensitive equality match                    |
| `titleContainsFold` | `String`    | Case-insensitive substring match                   |
| `titleIsNil`        | `Boolean`   | Title is not set (matches missing or empty string) |
| `titleNotNil`       | `Boolean`   | Title is set to a non-empty value                  |

### Group Title (pyck\_group\_title search attribute)

These predicates match the `pyck_group_title` Temporal search attribute, the human-readable label for the workflow group header. It pairs with `groupBy` (the technical join key), and is written via `workflowsdk.SetGroupTitle`.

| Filter                   | Type        | Description                                              |
| ------------------------ | ----------- | -------------------------------------------------------- |
| `groupTitle`             | `String`    | Exact group title match                                  |
| `groupTitleNEQ`          | `String`    | Not equal to group title                                 |
| `groupTitleIn`           | `[String!]` | Match any of the provided group titles                   |
| `groupTitleNotIn`        | `[String!]` | Exclude specific group titles                            |
| `groupTitleContains`     | `String`    | Group title contains substring (case-sensitive)          |
| `groupTitleHasPrefix`    | `String`    | Group title starts with                                  |
| `groupTitleHasSuffix`    | `String`    | Group title ends with                                    |
| `groupTitleEqualFold`    | `String`    | Case-insensitive equality match                          |
| `groupTitleContainsFold` | `String`    | Case-insensitive substring match                         |
| `groupTitleIsNil`        | `Boolean`   | Group title is not set (matches missing or empty string) |
| `groupTitleNotNil`       | `Boolean`   | Group title is set to a non-empty value                  |

### Sort Key (pyck\_sort\_key search attribute)

The `pyck_sort_key` search attribute is a numeric value used by the UI to impose a stable display order on workflow executions. When not set, workflows default to start-time ordering.

| Filter          | Type      | Description                         |
| --------------- | --------- | ----------------------------------- |
| `sortKey`       | `Int`     | Exact sort key match                |
| `sortKeyNEQ`    | `Int`     | Not equal to sort key               |
| `sortKeyIn`     | `[Int!]`  | Match any of the provided sort keys |
| `sortKeyNotIn`  | `[Int!]`  | Exclude specific sort keys          |
| `sortKeyGT`     | `Int`     | Sort key greater than               |
| `sortKeyGTE`    | `Int`     | Sort key greater than or equal      |
| `sortKeyLT`     | `Int`     | Sort key less than                  |
| `sortKeyLTE`    | `Int`     | Sort key less than or equal         |
| `sortKeyIsNil`  | `Boolean` | Sort key is not set                 |
| `sortKeyNotNil` | `Boolean` | Sort key is set                     |

### Logical Operators

| Filter | Type                              | Description               |
| ------ | --------------------------------- | ------------------------- |
| `and`  | `[WorkflowExecutionsWhereInput!]` | All conditions must match |
| `or`   | `[WorkflowExecutionsWhereInput!]` | Any condition matches     |
| `not`  | `WorkflowExecutionsWhereInput`    | Negate condition          |

## Ordering Options (WorkflowExecutionOrder)

| Field       | Values                                                                                  | Description      |
| ----------- | --------------------------------------------------------------------------------------- | ---------------- |
| `direction` | `ASC`, `DESC`                                                                           | Sort direction   |
| `field`     | `START_TIME`, `CLOSE_TIME`, `WORKFLOW_ID`, `STATUS`, `TITLE`, `GROUP_TITLE`, `SORT_KEY` | Field to sort by |

`TITLE` orders by the `pyck_title` search attribute and `GROUP_TITLE` orders by the `pyck_group_title` search attribute, enabling alphabetical sorting of workflows by their human-readable display label or group header. `SORT_KEY` orders by the numeric `pyck_sort_key` search attribute, giving the UI an explicit display position independent of start time.

## Usage Examples

### Basic Query with Pagination

```graphql
query {
  workflowExecutions(
    first: 50
    orderBy: { direction: DESC, field: START_TIME }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        closeTime
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

### Filter by Status and Type

```graphql
query {
  workflowExecutions(
    where: {
      typeName: "PickingWorkflow"
      status: "RUNNING"
    }
    first: 100
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        historyLength
        searchAttributes {
          key
          value
        }
      }
    }
    totalCount
  }
}
```

### Complex Filtering with AND

```graphql
query {
  workflowExecutions(
    where: {
      and: [
        { typeNameIn: ["PickingWorkflow", "ReceivingWorkflow"] }
        { statusNotIn: ["COMPLETED", "FAILED"] }
        { startTimeGTE: "2024-01-01T00:00:00Z" }
        { assigneeNotNil: true }
      ]
    }
    first: 50
    orderBy: { direction: ASC, field: START_TIME }
  ) {
    edges {
      node {
        execution {
          workflowId
        }
        status
        startTime
        searchAttributes {
          key
          value
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Using OR Operator

Find workflows that are either unassigned or not assigned to a specific user:

```graphql
query {
  workflowExecutions(
    where: {
      or: [
        { assigneeIsNil: true }
        { assigneeNeq: "user-123" }
      ]
    }
    first: 50
  ) {
    edges {
      node {
        execution {
          workflowId
        }
        status
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

Find workflows in multiple statuses from different services:

```graphql
query {
  workflowExecutions(
    where: {
      or: [
        {
          and: [
            { service: "picking" }
            { status: "RUNNING" }
          ]
        }
        {
          and: [
            { service: "receiving" }
            { statusIn: ["RUNNING", "PENDING"] }
          ]
        }
      ]
    }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
        status
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

### Using NOT Operator

Exclude specific workflow types:

```graphql
query {
  workflowExecutions(
    where: {
      not: {
        typeNameIn: ["TestWorkflow", "DebugWorkflow"]
      }
      status: "RUNNING"
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        type { name }
        status
      }
    }
  }
}
```

### Combining OR, AND, and NOT

Find active workflows that are either high priority or assigned to a specific team:

```graphql
query {
  workflowExecutions(
    where: {
      and: [
        {
          not: {
            statusIn: ["COMPLETED", "FAILED", "CANCELED"]
          }
        }
        {
          or: [
            { workflowNameContains: "URGENT" }
            { assigneeHasPrefix: "team-alpha-" }
          ]
        }
      ]
    }
    first: 50
    orderBy: { direction: DESC, field: START_TIME }
  ) {
    edges {
      node {
        execution { workflowId }
        status
        startTime
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

### Using String Predicates

Case-insensitive search with suffix matching:

```graphql
query {
  workflowExecutions(
    where: {
      # Case-insensitive search for workflow names ending with "order"
      workflowNameHasSuffix: "order"
      workflowNameEqualFold: "picking-order"
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
  }
}
```

Search workflows with case-insensitive substring matching:

```graphql
query {
  workflowExecutions(
    where: {
      # Find workflows containing "test" (case-insensitive)
      workflowNameContainsFold: "test"
      # Match data IDs ending with specific pattern
      dataIdHasSuffix: "-batch-001"
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

### Paginating Through Results

```graphql
# First page
query FirstPage {
  workflowExecutions(
    where: { service: "picking" }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

# Next page (use endCursor from previous response)
query NextPage {
  workflowExecutions(
    where: { service: "picking" }
    first: 100
    after: "eyJzdGFydFRpbWUiOiIyMDI0LTAxLTE1VDEwOjMwOjAwWiJ9"
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Find Specific Workflow

```graphql
query {
  workflowExecutions(
    where: {
      workflowID: "picking-order-12345"
    }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        type {
          name
        }
        status
        startTime
        closeTime
        historyLength
        historySizeBytes
        taskQueue
        executionDuration
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

### Filter by Title or Group Title

Find workflows whose display label matches an exact value:

```graphql
query {
  workflowExecutions(
    where: {
      title: "SKU-123"
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

Find workflows whose title shares a common prefix and sort them alphabetically:

```graphql
query {
  workflowExecutions(
    where: {
      titleHasPrefix: "SKU-"
    }
    first: 100
    orderBy: { direction: ASC, field: TITLE }
  ) {
    edges {
      node {
        execution { workflowId }
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

Find workflows that have not yet had a title set (treats missing attribute or empty string as null):

```graphql
query {
  workflowExecutions(
    where: {
      titleIsNil: true
      status: "RUNNING"
    }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
  }
}
```

Group workflows under a shared group header and sort them by group title:

```graphql
query {
  workflowExecutions(
    where: {
      groupTitleHasPrefix: "ORDER-"
    }
    first: 100
    orderBy: { direction: ASC, field: GROUP_TITLE }
  ) {
    edges {
      node {
        execution { workflowId }
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

Restrict to a known set of group titles:

```graphql
query {
  workflowExecutions(
    where: {
      groupTitleIn: ["ORDER-42", "ORDER-43"]
    }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
      }
    }
  }
}
```

### Filter by Data Type and Service

```graphql
query {
  workflowExecutions(
    where: {
      service: "picking"
      dataType: "picking-order"
    }
    first: 50
  ) {
    edges {
      node {
        execution {
          workflowId
        }
        status
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

### Filter by Sort Key

Find workflows with a specific sort key for ordering:

```graphql
query {
  workflowExecutions(
    where: {
      sortKey: 42
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
        searchAttributes {
          key
          value
        }
      }
    }
  }
}
```

Find workflows within a sort key range:

```graphql
query {
  workflowExecutions(
    where: {
      sortKeyGTE: 10
      sortKeyLTE: 99
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
  }
}
```

### Order by Sort Key

Order workflows by their numeric display position:

```graphql
query {
  workflowExecutions(
    where: {
      status: "RUNNING"
    }
    orderBy: { direction: ASC, field: SORT_KEY }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
        startTime
      }
    }
  }
}
```

Find workflows that don't have a sort key set (will use default ordering):

```graphql
query {
  workflowExecutions(
    where: {
      sortKeyIsNil: true
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
  }
}
```

## Example Response

```json
{
  "data": {
    "workflowExecutions": {
      "edges": [
        {
          "node": {
            "execution": {
              "workflowId": "picking-order-12345",
              "id": "run-abc-123"
            },
            "type": {
              "name": "PickingWorkflow"
            },
            "status": "RUNNING",
            "startTime": "2024-01-15T10:30:00Z",
            "closeTime": null,
            "historyLength": 42,
            "searchAttributes": [
              { "key": "pyck_title", "value": "Picking Order #12345" },
              { "key": "pyck_group_title", "value": "Zone A" }
            ]
          },
          "cursor": "eyJzdGFydFRpbWUiOiIyMDI0LTAxLTE1VDEwOjMwOjAwWiJ9"
        }
      ],
      "pageInfo": {
        "hasNextPage": true,
        "endCursor": "eyJzdGFydFRpbWUiOiIyMDI0LTAxLTE1VDEwOjMwOjAwWiJ9"
      },
      "totalCount": 150
    }
  }
}
```

## Breaking Changes

This query has undergone significant changes:

1. **Return type changed** from `[WorkflowExecutionInfo!]!` to `WorkflowExecutionInfoConnection!`
2. **Pagination support added** via `first` and `after` parameters
3. **Ordering support added** via `orderBy` parameter
4. **History not included** - use `workflowHistory` query for history events
5. **`memo` field removed from `WorkflowExecutionInfo`** - per-workflow titles now live in the `pyck_title` and `pyck_group_title` search attributes. New `title*` and `groupTitle*` predicates and the `TITLE` / `GROUP_TITLE` order fields let you filter and sort on them server-side.

See [WorkflowExecutionInfo](/graphql-api/types/workflowexecutioninfo) for migration examples.

## Notes

* Returns lightweight execution metadata WITHOUT history for performance
* Use `workflowHistory` query to fetch history for specific executions
* Pagination uses Temporal's NextPageToken directly
* Default page size is 100 if `first` is not specified
* Results can be ordered by start time, close time, workflow ID, status, title, or group title
* **Logical operators** (`or`, `and`, `not`) are fully supported for building complex queries
* **String predicates** include case-sensitive (`hasPrefix`, `hasSuffix`, `contains`) and case-insensitive (`equalFold`, `containsFold`) variants
* **Case-insensitive predicates** (`equalFold`, `containsFold`) map to the same Temporal operators as their case-sensitive counterparts since Temporal doesn't have native case-insensitive operators

### Filter by Targets

Find workflows that target the mobile surface:

```graphql
query {
  workflowExecutions(
    where: {
      targets: [MOBILE]
      status: "RUNNING"
    }
    first: 50
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
    totalCount
  }
}
```

Find workflows that target either web or mobile (KeywordList semantics — the workflow's target list need only contain one of these):

```graphql
query {
  workflowExecutions(
    where: {
      targets: [WEB, MOBILE]
    }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
      }
    }
  }
}
```

Exclude workflows targeting the setup surface:

```graphql
query {
  workflowExecutions(
    where: {
      targetsNotIn: [SETUP]
      status: "RUNNING"
    }
    first: 100
  ) {
    edges {
      node {
        execution { workflowId }
        status
      }
    }
  }
}
```

## Related Documentation

* [workflowHistory](/graphql-api/queries/workflowhistory) - Fetch workflow history events
* [workflowTargets](/graphql-api/queries/workflowtargets) - Read the current target surfaces of a workflow execution
* [setWorkflowTargets](/graphql-api/mutations/setworkflowtargets) - Replace the target surfaces of a workflow
* [WorkflowTarget](/graphql-api/enums/workflowtarget) - Enum of supported workflow target surfaces
* [WorkflowExecutionInfo](/graphql-api/types/workflowexecutioninfo) - Execution info type
* [WorkflowExecutionInfoConnection](/graphql-api/types/workflowexecutioninfoconnection) - Connection type
* [WorkflowEvent](/graphql-api/types/workflowevent) - History event type


# WorkflowHistory

Query workflow history events for specific executions

Audience: Programmer

Fetches workflow history events for executions matching the filter criteria. This query is designed to retrieve the complete history for specific workflow executions, replacing the removed `history` field from `WorkflowExecutionInfo`.

Use this query when you need to inspect workflow execution details, debug workflow behavior, or display workflow event timelines.

## Arguments

| Name    | Type                            | Description                                                                |
| ------- | ------------------------------- | -------------------------------------------------------------------------- |
| `where` | `WorkflowExecutionsWhereInput!` | Filter criteria for workflow executions (required)                         |
| `limit` | `Int`                           | Maximum number of executions to fetch history for. Defaults to 10, max 100 |

## Return Type

`WorkflowExecutionHistoryConnection!` - A connection containing workflow executions with their history events.

### Connection Fields

| Field        | Type                               | Description                              |
| ------------ | ---------------------------------- | ---------------------------------------- |
| `edges`      | `[WorkflowExecutionHistoryEdge!]!` | List of workflow execution history edges |
| `pageInfo`   | `WorkflowPageInfo!`                | Pagination information                   |
| `totalCount` | `Int!`                             | Total count of matching executions       |

### Edge Fields

| Field    | Type                        | Description                         |
| -------- | --------------------------- | ----------------------------------- |
| `node`   | `WorkflowExecutionHistory!` | The workflow execution with history |
| `cursor` | `String!`                   | Cursor for pagination               |

### WorkflowExecutionHistory Fields

| Field       | Type                 | Description                           |
| ----------- | -------------------- | ------------------------------------- |
| `execution` | `WorkflowExecution!` | The workflow execution identifier     |
| `typeName`  | `String!`            | The workflow type name                |
| `history`   | `[WorkflowEvent!]!`  | All history events for this execution |

## Filter Options

The `where` parameter accepts the same `WorkflowExecutionsWhereInput` as the `workflowExecutions` query, including support for logical operators (`or`, `and`, `not`) and advanced string predicates.

For complete documentation of all available filters, see [workflowExecutions](/graphql-api/queries/workflowexecutions#filter-options-workflowexecutionswhereinput).

Common filters for history retrieval include:

| Filter         | Type        | Description                                          |
| -------------- | ----------- | ---------------------------------------------------- |
| `workflowID`   | `String`    | Exact workflow ID (recommended for single execution) |
| `runID`        | `String`    | Specific run ID                                      |
| `workflowIDIn` | `[String!]` | Multiple workflow IDs                                |
| `typeName`     | `String`    | Filter by workflow type                              |
| `status`       | `String`    | Filter by status                                     |

## Usage Examples

### Get History for a Single Execution

```graphql
query {
  workflowHistory(
    where: {
      workflowID: "picking-order-12345"
    }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        typeName
        history {
          eventId
          eventTime
          eventType
          extra
        }
      }
    }
    totalCount
  }
}
```

### Get History for Specific Run

```graphql
query {
  workflowHistory(
    where: {
      workflowID: "picking-order-12345"
      runID: "run-abc-123"
    }
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        typeName
        history {
          eventId
          eventTime
          eventType
          extra
        }
      }
    }
  }
}
```

### Get History for Multiple Executions

```graphql
query {
  workflowHistory(
    where: {
      workflowIDIn: [
        "picking-order-12345",
        "picking-order-12346",
        "picking-order-12347"
      ]
    }
    limit: 10
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        typeName
        history {
          eventId
          eventTime
          eventType
        }
      }
    }
    totalCount
  }
}
```

### Get History for Failed Workflows

```graphql
query {
  workflowHistory(
    where: {
      typeName: "PickingWorkflow"
      status: "FAILED"
    }
    limit: 5
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
        typeName
        history {
          eventId
          eventTime
          eventType
          extra
        }
      }
    }
    totalCount
  }
}
```

### Get History by Service and Data Type

```graphql
query {
  workflowHistory(
    where: {
      service: "picking"
      dataType: "picking-order"
      dataId: "order-123"
    }
  ) {
    edges {
      node {
        execution {
          workflowId
        }
        history {
          eventId
          eventType
          eventTime
        }
      }
    }
  }
}
```

## Example Response

```json
{
  "data": {
    "workflowHistory": {
      "edges": [
        {
          "node": {
            "execution": {
              "workflowId": "picking-order-12345",
              "id": "run-abc-123"
            },
            "typeName": "PickingWorkflow",
            "history": [
              {
                "eventId": 1,
                "eventTime": "2024-01-15T10:30:00Z",
                "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",
                "extra": {
                  "workflowType": {
                    "name": "PickingWorkflow"
                  },
                  "taskQueue": {
                    "name": "picking-queue"
                  }
                }
              },
              {
                "eventId": 2,
                "eventTime": "2024-01-15T10:30:01Z",
                "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
                "extra": {}
              },
              {
                "eventId": 3,
                "eventTime": "2024-01-15T10:30:01Z",
                "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
                "extra": {}
              },
              {
                "eventId": 4,
                "eventTime": "2024-01-15T10:30:02Z",
                "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
                "extra": {}
              },
              {
                "eventId": 5,
                "eventTime": "2024-01-15T10:30:02Z",
                "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
                "extra": {
                  "activityType": {
                    "name": "ValidateOrderActivity"
                  }
                }
              }
            ]
          },
          "cursor": "eyJ3b3JrZmxvd0lkIjoicGlja2luZy1vcmRlci0xMjM0NSJ9"
        }
      ],
      "pageInfo": {
        "hasNextPage": false,
        "hasPreviousPage": false,
        "startCursor": "eyJ3b3JrZmxvd0lkIjoicGlja2luZy1vcmRlci0xMjM0NSJ9",
        "endCursor": "eyJ3b3JrZmxvd0lkIjoicGlja2luZy1vcmRlci0xMjM0NSJ9"
      },
      "totalCount": 1
    }
  }
}
```

## Common Event Types

| Event Type                                                | Description                        |
| --------------------------------------------------------- | ---------------------------------- |
| `EVENT_TYPE_WORKFLOW_EXECUTION_STARTED`                   | Workflow began execution           |
| `EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED`                 | Workflow completed successfully    |
| `EVENT_TYPE_WORKFLOW_EXECUTION_FAILED`                    | Workflow failed with error         |
| `EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED`                  | Workflow was canceled              |
| `EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED`                | Workflow was forcefully terminated |
| `EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT`                 | Workflow exceeded timeout          |
| `EVENT_TYPE_WORKFLOW_TASK_SCHEDULED`                      | Task scheduled for worker          |
| `EVENT_TYPE_WORKFLOW_TASK_STARTED`                        | Worker started task                |
| `EVENT_TYPE_WORKFLOW_TASK_COMPLETED`                      | Worker completed task              |
| `EVENT_TYPE_ACTIVITY_TASK_SCHEDULED`                      | Activity scheduled                 |
| `EVENT_TYPE_ACTIVITY_TASK_STARTED`                        | Activity started                   |
| `EVENT_TYPE_ACTIVITY_TASK_COMPLETED`                      | Activity completed                 |
| `EVENT_TYPE_ACTIVITY_TASK_FAILED`                         | Activity failed                    |
| `EVENT_TYPE_TIMER_STARTED`                                | Timer started                      |
| `EVENT_TYPE_TIMER_FIRED`                                  | Timer fired                        |
| `EVENT_TYPE_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED` | Signal sent to another workflow    |
| `EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED`                  | Workflow received signal           |

## Performance Considerations

* The `limit` parameter defaults to 10 and has a maximum of 100
* Fetching history for many executions can be resource-intensive
* For best performance, query specific workflows by `workflowID` or `runID`
* History events are returned in full; there is no pagination within a single execution's history
* Consider using `workflowExecutions` first to identify specific executions, then query their history

## Migration from history Field

If you were previously using the `history` field on `WorkflowExecutionInfo`:

**Before:**

```graphql
query {
  workflowExecutions(where: { workflowID: "my-workflow" }) {
    execution { workflowId }
    history {
      eventId
      eventType
    }
  }
}
```

**After:**

```graphql
query {
  workflowHistory(where: { workflowID: "my-workflow" }) {
    edges {
      node {
        execution { workflowId }
        history {
          eventId
          eventType
        }
      }
    }
  }
}
```

## Notes

* The `where` parameter is **required** - you must specify filter criteria
* Returns all history events for each matching execution (no pagination within history)
* Use the `limit` parameter to control how many executions' histories are fetched
* This query replaces the removed `history` field from `WorkflowExecutionInfo`
* The `extra` field in history events contains event-specific details
* **Logical operators** (`or`, `and`, `not`) are fully supported for building complex filter conditions

## Related Documentation

* [workflowExecutions](/graphql-api/queries/workflowexecutions) - Query execution metadata
* [WorkflowExecutionHistory](/graphql-api/types/workflowexecutionhistory) - History type
* [WorkflowExecutionHistoryConnection](/graphql-api/types/workflowexecutionhistoryconnection) - Connection type
* [WorkflowEvent](/graphql-api/types/workflowevent) - Event type
* [WorkflowExecutionInfo](/graphql-api/types/workflowexecutioninfo) - Execution info type


# WorkflowActions

Retrieve the queries and updates currently available for a workflow execution

Audience: Programmer

Returns the queries and updates that a workflow execution currently accepts, together with an `enabled` flag that indicates whether each action is callable at this moment. Because Temporal workflows register and deregister handlers as they progress, the result of this query changes dynamically during the lifetime of a workflow run and reflects the workflow's state at the time of the call.

This query is useful for building UIs that expose workflow controls to users: clients can discover which interactions are valid without hard-coding workflow knowledge, and can render or disable buttons based on the `enabled` flag.

## Arguments

| Name    | Type                        | Description                                             |
| ------- | --------------------------- | ------------------------------------------------------- |
| `input` | `GetWorkflowActionsInput!`  | Input identifying the workflow run (required)           |
| `where` | `WorkflowActionsWhereInput` | Optional filter that narrows which actions are returned |

### GetWorkflowActionsInput Fields

| Field                 | Type      | Description                                     |
| --------------------- | --------- | ----------------------------------------------- |
| `workflowId`          | `String!` | The unique identifier of the workflow           |
| `workflowExecutionId` | `String!` | The specific execution (run) ID of the workflow |

### WorkflowActionsWhereInput Fields

| Field              | Type        | Description                                                                             |
| ------------------ | ----------- | --------------------------------------------------------------------------------------- |
| `name`             | `String`    | Optional exact-match filter on the action name                                          |
| `nameNEQ`          | `String`    | Matches actions whose name is **not** equal to the value                                |
| `nameIn`           | `[String!]` | Matches actions whose name is in the provided list                                      |
| `nameNotIn`        | `[String!]` | Matches actions whose name is **not** in the provided list                              |
| `nameContains`     | `String`    | Matches actions whose name contains the substring (case-sensitive)                      |
| `nameHasPrefix`    | `String`    | Matches actions whose name starts with the prefix (case-sensitive)                      |
| `nameHasSuffix`    | `String`    | Matches actions whose name ends with the suffix (case-sensitive)                        |
| `nameEqualFold`    | `String`    | Matches actions whose name equals the value, ignoring case                              |
| `nameContainsFold` | `String`    | Matches actions whose name contains the substring, ignoring case                        |
| `enabled`          | `Boolean`   | Optional filter by enabled state. Pass `true` to only return currently callable actions |

All predicates are AND-joined; an action must satisfy every predicate you set. Unset predicates (omitted fields, `null`, empty strings, and empty lists) are ignored and match every action. See [WorkflowActionsWhereInput](/graphql-api/inputs/workflowactionswhereinput) for full details.

## Return Type

`GetWorkflowActionsResponse!` - A response containing two lists of registered actions (non-nullable).

### GetWorkflowActionsResponse Fields

| Field     | Type                   | Description                                      |
| --------- | ---------------------- | ------------------------------------------------ |
| `queries` | `[ActionDefinition!]!` | The queries registered on the workflow execution |
| `updates` | `[ActionDefinition!]!` | The updates registered on the workflow execution |

### ActionDefinition Fields

| Field         | Type       | Description                                                        |
| ------------- | ---------- | ------------------------------------------------------------------ |
| `name`        | `String!`  | The name under which the action is registered                      |
| `description` | `String`   | Optional human-readable description of what the action does        |
| `enabled`     | `Boolean!` | Whether the action is currently callable on the workflow execution |

## Usage Example

### GraphQL Query

```graphql
query GetWorkflowActions($input: GetWorkflowActionsInput!, $where: WorkflowActionsWhereInput) {
  workflowActions(input: $input, where: $where) {
    queries {
      description
      enabled
      name
    }
    updates {
      description
      enabled
      name
    }
  }
}
```

### Variables

```json
{
  "input": {
    "workflowExecutionId": "test-run-id",
    "workflowId": "workflow-id"
  },
  "where": {
    "enabled": true
  }
}
```

### JavaScript Example

```javascript
const query = `
  query GetWorkflowActions($input: GetWorkflowActionsInput!, $where: WorkflowActionsWhereInput) {
    workflowActions(input: $input, where: $where) {
      queries {
        description
        enabled
        name
      }
      updates {
        description
        enabled
        name
      }
    }
  }
`;

const variables = {
  input: {
    workflowId: "order-processing-workflow-123",
    workflowExecutionId: "run-456-xyz"
  },
  where: {
    enabled: true
  }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({ query, variables })
});

const result = await response.json();
const { queries, updates } = result.data.workflowActions;

console.log(`Callable queries: ${queries.map(q => q.name).join(', ')}`);
console.log(`Callable updates: ${updates.map(u => u.name).join(', ')}`);
```

## Response Example

```json
{
  "data": {
    "workflowActions": {
      "queries": [
        {
          "name": "getStatus",
          "description": "Returns the current status of the workflow",
          "enabled": true
        },
        {
          "name": "getProgress",
          "description": "Returns the picking progress as a percentage",
          "enabled": true
        }
      ],
      "updates": [
        {
          "name": "confirmPick",
          "description": "Confirm that a pick has been completed",
          "enabled": true
        }
      ]
    }
  }
}
```

### Filtering by Name

Pass a `name` in the `where` argument to fetch a single action:

```graphql
query {
  workflowActions(
    input: {
      workflowId: "order-processing-workflow-123"
      workflowExecutionId: "run-456-xyz"
    }
    where: { name: "confirmPick" }
  ) {
    updates {
      name
      enabled
      description
    }
  }
}
```

### Filtering by Name Predicate

Beyond exact matches, you can filter using string predicates such as `nameHasPrefix`, `nameContains`, or `nameIn`. The following query returns only the callable actions whose name starts with `ship`:

```graphql
query {
  workflowActions(
    input: {
      workflowId: "order-processing-workflow-123"
      workflowExecutionId: "run-456-xyz"
    }
    where: {
      nameHasPrefix: "ship"
      enabled: true
    }
  ) {
    updates {
      name
      enabled
      description
    }
  }
}
```

Predicates combine with AND, so the example above returns an action only if its name starts with `ship` **and** it is currently callable. For a case-insensitive match, use `nameContainsFold` or `nameEqualFold` instead.

## Error Handling

The query may return errors in the following cases:

### Invalid WorkflowID

```json
{
  "errors": [{
    "message": "invalid workflowId",
    "path": ["workflowActions"]
  }]
}
```

### Invalid WorkflowExecutionID

```json
{
  "errors": [{
    "message": "invalid workflowExecutionId",
    "path": ["workflowActions"]
  }]
}
```

### Workflow Not Found

```json
{
  "errors": [{
    "message": "workflow not found: order-processing-workflow-123",
    "path": ["workflowActions"]
  }]
}
```

### Workflow Execution Completed

Workflow executions that have already completed no longer expose callable queries or updates. In that case, both `queries` and `updates` are typically empty or all actions are returned with `enabled: false`.

## Notes

* The result is a snapshot in time. Because Temporal workflows can register and deregister handlers as they progress, calling `workflowActions` again later may return a different set of actions.
* The `enabled` flag reflects whether the action is callable right now. A handler may be registered but temporarily disabled while the workflow is in a particular state.
* Use the `where` argument to reduce the payload when you are only interested in currently callable actions or actions matching a name predicate (exact match, prefix, suffix, substring, or list membership).
* Action definitions are filtered in memory after the full set is fetched, so all predicates in `where` are AND-joined and evaluated directly against each action name.
* Queries returned by this endpoint are Temporal workflow queries (read-only), while updates are Temporal workflow updates (can modify workflow state).
* Requires valid authentication and appropriate tenant context.

## Related Types

* [GetWorkflowActionsInput](/graphql-api/inputs/getworkflowactionsinput)
* [WorkflowActionsWhereInput](/graphql-api/inputs/workflowactionswhereinput)
* [GetWorkflowActionsResponse](/graphql-api/types/getworkflowactionsresponse)
* [ActionDefinition](/graphql-api/types/actiondefinition)

## Service

This query is provided by the **workflow** service as part of the federated GraphQL schema.


# WorkflowSignals

Workflow Signals Query

Returns a paginated list of WorkflowSignal objects, with optional filtering and ordering. Workflow signals define events that can start or control workflow executions in the Temporal workflow engine.

## Arguments

| Name      | Type                       | Description                                                            |
| --------- | -------------------------- | ---------------------------------------------------------------------- |
| `after`   | `Cursor`                   | Returns the elements in the list that come after the specified cursor  |
| `first`   | `Int`                      | Returns the first *n* elements from the list                           |
| `before`  | `Cursor`                   | Returns the elements in the list that come before the specified cursor |
| `last`    | `Int`                      | Returns the last *n* elements from the list                            |
| `orderBy` | `WorkflowSignalOrder`      | Ordering options for workflow signals returned from the connection     |
| `where`   | `WorkflowSignalWhereInput` | Filtering options for workflow signals returned from the connection    |

## Return Type

`WorkflowSignalConnection!` - A connection to a list of WorkflowSignal objects with pagination information.

## Usage Example

```graphql
query {
  # Get workflow signals that start workflows
  workflowSignals(
    where: {
      start: true
    },
    orderBy: { direction: DESC, field: CREATED_AT }
  ) {
    edges {
      node {
        id
        workflowID
        eventName
        start
        dataTypeSlug
        data
        createdAt
        workflow {
          id
          name
          active
        }
      }
      cursor
    }
    totalCount
  }
}
```

```graphql
query {
  # Search signals by event name
  workflowSignals(
    where: {
      eventNameContains: "order"
    },
    first: 20
  ) {
    edges {
      node {
        id
        workflowID
        eventName
        start
        data
        workflow {
          id
          name
          active
          filterRule
        }
      }
    }
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
  }
}
```

```graphql
query {
  # Get signals for specific workflow
  workflowSignals(
    where: {
      workflowID: "01234567-89ab-cdef-0123-456789abcdef"
    }
  ) {
    edges {
      node {
        id
        eventName
        start
        data
        createdAt
        workflow {
          name
          active
        }
      }
    }
  }
}
```

## Common Filters

* `eventNameContains` - Search by event name substring
* `eventName` - Find by exact event name
* `start` - Filter by whether signal starts workflow
* `workflowID` - Filter by associated workflow
* `dataTypeSlug` - Filter by data type slug
* `hasWorkflow` - Filter signals that have associated workflow
* `hasWorkflowWith` - Filter by workflow criteria
* `tenantID` - Filter by tenant

## Notes

* Workflow signals connect events to workflow executions
* Start signals trigger new workflow instances
* Non-start signals control existing workflow instances
* Event names correspond to business events in the system
* Integration with Temporal.io workflow engine for reliable processing
* Support custom fields through data/dataType system
* Essential for event-driven workflow orchestration and process automation


# WorkflowTargets

Read the current target surfaces of a workflow execution

Audience: Programmer

Reads the current target surfaces of a single workflow execution. Returns an empty list when the workflow has not declared any targets.

The target surfaces are stored in the `pyck_workflow_targets` KeywordList search attribute in Temporal and represent the client surfaces (such as web, mobile, or setup) for which the workflow is intended.

## Arguments

| Name    | Type                       | Description                                      |
| ------- | -------------------------- | ------------------------------------------------ |
| `input` | `GetWorkflowTargetsInput!` | Input containing workflow identifiers (required) |

### GetWorkflowTargetsInput Fields

| Field                 | Type      | Description                                   |
| --------------------- | --------- | --------------------------------------------- |
| `workflowId`          | `String!` | The unique identifier of the workflow         |
| `workflowExecutionId` | `String!` | The specific run ID of the workflow execution |

## Return Type

`GetWorkflowTargetsResponse!` - Response containing the list of target surfaces (non-nullable).

### GetWorkflowTargetsResponse Fields

| Field     | Type                 | Description                                                                    |
| --------- | -------------------- | ------------------------------------------------------------------------------ |
| `targets` | `[WorkflowTarget!]!` | The list of currently declared target surfaces. Empty when no targets are set. |

## Usage Example

### GraphQL Query

```graphql
query GetWorkflowTargets {
  workflowTargets(input: {
    workflowId: "picking-order-12345"
    workflowExecutionId: "run-abc-123"
  }) {
    targets
  }
}
```

### JavaScript Example

```javascript
const query = `
  query GetWorkflowTargets($input: GetWorkflowTargetsInput!) {
    workflowTargets(input: $input) {
      targets
    }
  }
`;

const variables = {
  input: {
    workflowId: "picking-order-12345",
    workflowExecutionId: "run-abc-123"
  }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    query,
    variables
  })
});

const result = await response.json();
console.log('Targets:', result.data.workflowTargets.targets);
// Output: [ 'WEB', 'MOBILE' ]
```

## Response Example

### Workflow with Targets Declared

```json
{
  "data": {
    "workflowTargets": {
      "targets": ["WEB", "MOBILE"]
    }
  }
}
```

### Workflow Without Targets

When no targets have been declared, the field returns an empty list:

```json
{
  "data": {
    "workflowTargets": {
      "targets": []
    }
  }
}
```

## Filtering Workflow Executions by Target

The targets exposed by this query are also indexed as the `pyck_workflow_targets` KeywordList search attribute. They can be combined with filtering queries:

```graphql
query {
  workflowExecutions(
    where: {
      targets: [WEB]
      status: "RUNNING"
    }
    first: 50
  ) {
    edges {
      node {
        execution {
          workflowId
          id
        }
      }
    }
  }
}
```

## Error Handling

The query may return errors in the following cases:

### Invalid WorkflowId

```json
{
  "errors": [{
    "message": "invalid WorkflowID",
    "path": ["workflowTargets"]
  }]
}
```

### Invalid WorkflowExecutionId

```json
{
  "errors": [{
    "message": "invalid WorkflowExecutionID",
    "path": ["workflowTargets"]
  }]
}
```

### Workflow Not Found

```json
{
  "errors": [{
    "message": "workflow not found: picking-order-12345",
    "path": ["workflowTargets"]
  }]
}
```

## Notes

* Targets are stored in Temporal's search attribute `pyck_workflow_targets` (KeywordList)
* An empty `targets` array is returned for workflows that have not declared any targets
* The query is read-only and does not affect the workflow execution
* Target values must be valid `WorkflowTarget` enum values (`WEB`, `MOBILE`, `SETUP`)
* Use [setWorkflowTargets](/graphql-api/mutations/setworkflowtargets) to update targets at runtime

## Related Documentation

* Mutation: [setWorkflowTargets](/graphql-api/mutations/setworkflowtargets)
* Input: [GetWorkflowTargetsInput](/graphql-api/inputs/getworkflowtargetsinput)
* Type: [GetWorkflowTargetsResponse](/graphql-api/types/getworkflowtargetsresponse)
* Enum: [WorkflowTarget](/graphql-api/enums/workflowtarget)
* Query: [workflowExecutions](/graphql-api/queries/workflowexecutions)

## Service

This query is provided by the **workflow** service as part of the federated GraphQL schema.


# Service Status

Service health and status monitoring queries

Audience: System Administrator

pyck provides dedicated queries for monitoring the health and status of each microservice in the system. These queries are essential for:

* Health checks and monitoring
* Deployment verification
* Version tracking
* Service availability monitoring

## Available Service Status Queries

Each pyck service exposes a status query that returns `ServiceInfo` with version and deployment information:

* **inventory** - Inventory service status
* **main\_data** - Main data service status
* **management** - Management service status
* **picking** - Picking service status
* **receiving** - Receiving service status
* **file** - File service status
* **workflow** - Workflow service status

## Return Type

All service status queries return the `ServiceInfo` type containing:

* `version` - Service version string
* `date` - Build/deployment date

## Usage Example

```graphql
query {
  inventory {
    version
    date
  }
  picking {
    version
    date
  }
}
```

## Monitoring Best Practices

1. **Regular Health Checks**: Set up automated queries to monitor service availability
2. **Version Tracking**: Track version numbers across deployments
3. **Alert Configuration**: Configure alerts when services become unavailable
4. **Dashboard Integration**: Integrate status queries into monitoring dashboards

## See Also

* [ServiceInfo Type](/graphql-api/types/serviceinfo) - Details about the ServiceInfo return type


# Inventory Status

Get inventory service status and version information

Audience: System Administrator

Returns the current status and version information for the inventory service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  inventory {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "inventory": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Main Data Status

Get main data service status and version information

Audience: System Administrator

Returns the current status and version information for the main data service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  main_data {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "main_data": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Management Status

Get management service status and version information

Audience: System Administrator

Returns the current status and version information for the management service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  management {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "management": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Picking Status

Get picking service status and version information

Audience: System Administrator

Returns the current status and version information for the picking service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  picking {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "picking": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Receiving Status

Get receiving service status and version information

Audience: System Administrator

Returns the current status and version information for the receiving service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  receiving {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "receiving": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# File Status

Get file service status and version information

Audience: System Administrator

Returns the current status and version information for the file service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  file {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "file": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Workflow Status

Get workflow service status and version information

Audience: System Administrator

Returns the current status and version information for the workflow service. This query is useful for health checks, monitoring, and deployment verification.

## Arguments

This query accepts no arguments.

## Return Type

`ServiceInfo!` - Service status information (non-nullable)

## Usage Example

```graphql
query {
  workflow {
    version
    date
  }
}
```

## Response Example

```json
{
  "data": {
    "workflow": {
      "version": "1.2.3",
      "date": "2024-01-15T10:30:00Z"
    }
  }
}
```

## Notes

* This query is marked with `@public` directive, meaning it doesn't require authentication
* Useful for monitoring service health and deployment status
* Can be combined with other service status queries in a single request

## Related Types

* [ServiceInfo](/graphql-api/types/serviceinfo)


# Mutations

GraphQL Mutations

This section documents all available mutations in the pyck GraphQL API. Mutations allow you to create, update, and delete data in the system.

## Available Mutations

### Management Service

#### Device Management

* [**createDevice**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/createDevice.md): Create a new device (scanner, printer, terminal)
* [**updateDevice**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateDevice.md): Update an existing device
* [**deleteDevice**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/deleteDevice.md): Delete a device from the system
* [**checkInUserDevice**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/checkInUserDevice.md): Assign a device to a user
* [**checkOutUserDevice**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/checkOutUserDevice.md): Return a device from a user

#### Location Management

* [**createLocation**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/createLocation.md): Create a new warehouse location
* [**updateLocation**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateLocation.md): Update an existing location
* [**deleteLocation**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/deleteLocation.md): Delete a location from the system
* [**setDeviceLocation**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/setDeviceLocation.md): Assign a device to a location
* [**unsetDeviceLocation**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/unsetDeviceLocation.md): Remove a device from a location

#### Customer & Supplier Management

* [**createCustomer**](/graphql-api/mutations/createcustomer): Create a new customer entity
* [**updateCustomer**](/graphql-api/mutations/updatecustomer): Update an existing customer with new data
* [**deleteCustomer**](/graphql-api/mutations/deletecustomer): Delete an existing customer from the system
* [**createSupplier**](/graphql-api/mutations/createsupplier): Create a new supplier entity
* [**updateSupplier**](/graphql-api/mutations/updatesupplier): Update an existing supplier with new data
* [**deleteSupplier**](/graphql-api/mutations/deletesupplier): Delete an existing supplier from the system

#### Data Types & Configuration

* [**createDataType**](/graphql-api/mutations/createdatatype): Create a new data type definition
* [**updateDataType**](/graphql-api/mutations/updatedatatype): Update an existing data type definition with new data
* [**deleteDataType**](/graphql-api/mutations/deletedatatype): Delete an existing data type definition from the system
* [**generateJsonSchema**](/graphql-api/mutations/generatejsonschema): Generate a JSON Schema definition from provided JSON data

#### System Management

* [**registerCompany**](/graphql-api/mutations/registercompany): Register a new company in the pyck system along with an initial admin user
* [**registerTenant**](/graphql-api/mutations/registertenant): Register a new tenant (organization) in the pyck system along with an initial admin user
* [**sendCustomEvent**](/graphql-api/mutations/sendcustomevent): Send a custom event to the pyck event system

### Inventory Service

* [**createInventoryItem**](/graphql-api/mutations/createinventoryitem): Create a new inventory item
* [**updateInventoryItem**](/graphql-api/mutations/updateinventoryitem): Update an existing inventory item with new data
* [**deleteInventoryItem**](/graphql-api/mutations/deleteinventoryitem): Delete an existing inventory item from the system
* [**createInventoryItemSet**](/graphql-api/mutations/createinventoryitemset): Create a new inventory item set for grouping related items
* [**updateInventoryItemSet**](/graphql-api/mutations/updateinventoryitemset): Update an existing inventory item set with new data
* [**deleteInventoryItemSet**](/graphql-api/mutations/deleteinventoryitemset): Delete an existing inventory item set from the system
* [**createInventoryCollectionMovement**](/graphql-api/mutations/createinventorycollectionmovement): Create a collection of related movements
* [**updateInventoryCollectionMovement**](/graphql-api/mutations/updateinventorycollectionmovement): Update an existing inventory collection movement with new data
* [**createInventoryItemMovement**](/graphql-api/mutations/createinventoryitemmovement): Create a movement to transfer items between repositories
* [**updateItemMovement**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateItemMovement.md): Update an existing item movement with new data
* [**deleteItemMovement**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/deleteItemMovement.md): Delete an existing item movement from the system
* [**executeItemMovement**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/executeItemMovement.md): Execute a pending movement
* [**createRepository**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/createRepository.md): Create a new storage location
* [**updateRepository**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateRepository.md): Update an existing repository with new data
* [**deleteInventoryRepository**](/graphql-api/mutations/deleteinventoryrepository): Delete an existing repository from the system
* [**updateRepositoryMovement**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateRepositoryMovement.md): Update an existing repository movement with new data
* [**deleteRepositoryMovement**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/deleteRepositoryMovement.md): Delete an existing repository movement from the system
* [**rebuildInventoryStock**](/graphql-api/mutations/rebuildinventorystock): Rebuild the inventory stock table to correct stock drift (admin only)

### Picking Service

* [**createPickingOrder**](/graphql-api/mutations/createpickingorder): Create a new picking order
* [**updatePickingOrder**](/graphql-api/mutations/updatepickingorder): Update an existing picking order with new data
* [**deletePickingOrder**](/graphql-api/mutations/deletepickingorder): Delete an existing picking order from the system
* [**createPickingOrderItem**](/graphql-api/mutations/createpickingorderitem): Create a new picking order item and associate it with an existing picking order
* [**updatePickingOrderItem**](/graphql-api/mutations/updatepickingorderitem): Update an existing picking order item with new data
* [**deletePickingOrderItem**](/graphql-api/mutations/deletepickingorderitem): Delete an existing picking order item from the system
* [**createPickingOutboundShipmentNotification**](/graphql-api/mutations/createpickingoutboundshipmentnotification): Create a new outbound shipment notification linked to a picking order
* [**updatePickingOutboundShipmentNotification**](/graphql-api/mutations/updatepickingoutboundshipmentnotification): Update an existing outbound shipment notification
* [**deletePickingOutboundShipmentNotification**](/graphql-api/mutations/deletepickingoutboundshipmentnotification): Delete an existing outbound shipment notification

### Receiving Service

* [**createReceivingInbound**](/graphql-api/mutations/createreceivinginbound): Create a new inbound receiving order
* [**updateReceivingInbound**](/graphql-api/mutations/updatereceivinginbound): Update an existing receiving inbound with new data
* [**deleteReceivingInbound**](/graphql-api/mutations/deletereceivinginbound): Delete an existing receiving inbound from the system
* [**createReceivingInboundItem**](/graphql-api/mutations/createreceivinginbounditem): Create a new receiving inbound item and associate it with an existing receiving order
* [**updateReceivingInboundItem**](/graphql-api/mutations/updatereceivinginbounditem): Update an existing receiving inbound item with new data
* [**deleteReceivingInboundItem**](/graphql-api/mutations/deletereceivinginbounditem): Delete an existing receiving inbound item from the system
* [**createReceivingInboundShipmentNotification**](/graphql-api/mutations/createreceivinginboundshipmentnotification): Create a new inbound shipment notification linked to a receiving inbound
* [**updateReceivingInboundShipmentNotification**](/graphql-api/mutations/updatereceivinginboundshipmentnotification): Update an existing inbound shipment notification
* [**deleteReceivingInboundShipmentNotification**](/graphql-api/mutations/deletereceivinginboundshipmentnotification): Delete an existing inbound shipment notification

### Workflow Service

* [**createWorkflow**](/graphql-api/mutations/createworkflow): Create a new workflow definition
* [**updateWorkflow**](/graphql-api/mutations/updateworkflow): Update an existing workflow definition with new data
* [**deleteWorkflow**](/graphql-api/mutations/deleteworkflow): Delete an existing workflow definition from the system
* [**createWorkflowSignal**](/graphql-api/mutations/createworkflowsignal): Create a new workflow signal event handler
* [**updateWorkflowSignal**](/graphql-api/mutations/updateworkflowsignal): Update an existing workflow signal with new data
* [**deleteWorkflowSignal**](/graphql-api/mutations/deleteworkflowsignal): Delete an existing workflow signal from the system
* [**checkWorkflowStatus**](/graphql-api/mutations/checkworkflowstatus): Check the status of a running workflow instance
* [**cancelWorkflow**](/graphql-api/mutations/cancelworkflow): Request graceful cancellation of a running workflow execution
* [**setAssignee**](/graphql-api/mutations/setassignee): Set or update the assignee for a running workflow instance
* [**setWorkflowTargets**](/graphql-api/mutations/setworkflowtargets): Replace the target surfaces of a running workflow execution

### File Service

* [**createFile**](/graphql-api/mutations/createfile): Upload and associate files with entities (the `size` input field is now optional)
* [**updateFile**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/updateFile.md): Update an existing file with new data
* [**deleteFile**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/deleteFile.md): Delete an existing file from the system
* [**finalizeFileUpload**](/graphql-api/mutations/finalize-file-upload): Finalize a file upload by reading the actual size from S3 and persisting it on the File record
* [**analyzeImageFile**](https://github.com/pyck-ai/docs/blob/main/graphql/mutations/analyzeImageFile.md): Analyze an image file using AI/ML services

## Mutation Structure

Mutations in GraphQL follow a standard structure:

```graphql
mutation {
  mutationName(input: {
    # Input fields specific to this mutation
    field1: value1
    field2: value2
  }) {
    # Return fields - what you want back after the mutation
    id
    field1
    field2
    createdAt
  }
}
```

## Working with Mutations

### Input Types

Most mutations use dedicated input types to specify the data for the operation. For example, the `createInventoryItem` mutation uses the `CreateInventoryItemInput` type.

### Return Types

Mutations typically return the affected entity, allowing you to retrieve updated values in the same operation.

### Error Handling

Mutations may return errors for various reasons:

* Invalid input data
* Insufficient permissions
* Conflicts with existing data
* Business rule violations

Refer to the [Error Handling](/graphql-api/error-handling) documentation for more information on handling errors.

## Example Mutation

Here's an example of creating a new inventory item:

```graphql
mutation {
  createInventoryItem(input: {
    name: "iPhone 13"
    sku: "IPHONE-13-BLACK"
    data: {
      weight: 173,
      color: "black",
      storage: "128GB"
    }
  }) {
    id
    name
    sku
    createdAt
    updatedAt
  }
}
```


# Analyze Image Attachment


# Cancel Workflow

cancelWorkflow Mutation

Audience: Programmer

Requests graceful cancellation of a running Temporal workflow execution.

The mutation delegates to Temporal's native cancellation mechanism. Unlike termination, cancellation is cooperative: the target workflow receives a cancellation signal (via `ctx.Done()`) and can run cleanup logic using `workflow.NewDisconnectedContext` before finally exiting. This makes cancellation the preferred way to stop long-running workflows while still releasing resources, emitting compensating events, or persisting final state.

The mutation returns once Temporal has accepted the cancel request. It does **not** wait for the workflow to actually reach a terminal state. Use the `checkWorkflowStatus` mutation or the `workflowExecutions` query to observe the eventual status transition to `CANCELED`.

## Arguments

| Name    | Type                   | Description                                 |
| ------- | ---------------------- | ------------------------------------------- |
| `input` | `CancelWorkflowInput!` | Identifies the workflow execution to cancel |

## Return Type

`CancelWorkflowPayload!` - Echoes the identifiers of the workflow execution whose cancellation was requested.

## Input Fields

`CancelWorkflowInput`:

| Field           | Type      | Description                                                                 |
| --------------- | --------- | --------------------------------------------------------------------------- |
| `workflowID`    | `String!` | The workflow ID (business-meaningful identifier) of the execution to cancel |
| `workflowRunID` | `String!` | The Temporal-generated run ID of the specific execution to cancel           |

## Return Fields

`CancelWorkflowPayload`:

| Field           | Type      | Description                                      |
| --------------- | --------- | ------------------------------------------------ |
| `workflowID`    | `String!` | The workflow ID whose cancellation was requested |
| `workflowRunID` | `String!` | The run ID whose cancellation was requested      |

## Usage Example

```graphql
mutation {
  cancelWorkflow(
    input: {
      workflowID: "picking-order-workflow-42",
      workflowRunID: "abc123de-f456-7890-ghij-klmnopqrstuv"
    }
  ) {
    workflowID
    workflowRunID
  }
}
```

## JavaScript Example

```javascript
const CANCEL_WORKFLOW = gql`
  mutation CancelWorkflow($input: CancelWorkflowInput!) {
    cancelWorkflow(input: $input) {
      workflowID
      workflowRunID
    }
  }
`;

const { data } = await client.mutate({
  mutation: CANCEL_WORKFLOW,
  variables: {
    input: {
      workflowID: "picking-order-workflow-42",
      workflowRunID: "abc123de-f456-7890-ghij-klmnopqrstuv"
    }
  }
});

console.log(
  `Cancellation requested for workflow ${data.cancelWorkflow.workflowID} (run ${data.cancelWorkflow.workflowRunID})`
);
```

## Behavior

* The resolver resolves the Temporal client for the caller's tenant via the workflow router; an invalid or unavailable client yields an `ErrInvalidWorkflowClient` error.
* On success, Temporal enqueues a `WorkflowExecutionCancelRequested` event on the target workflow history.
* The workflow code observes cancellation through `ctx.Err() == workflow.ErrCanceled` (or the `ctx.Done()` channel) and may run cleanup activities with a disconnected context before returning.
* The final workflow status will typically transition to `CANCELED`, though a workflow that ignores cancellation may still complete, fail, or time out.

## Error Handling

Possible errors include:

* **Invalid workflow client**: The tenant does not have a reachable Temporal client configured.
* **Workflow not found**: No execution exists for the provided `workflowID` / `workflowRunID` pair.
* **Workflow already closed**: The target execution is already in a terminal state (completed, failed, canceled, terminated, timed out).
* **Permission denied**: The caller is not authorized to cancel workflows in the target tenant.

## Important Notes

* Cancellation is cooperative and asynchronous. The mutation returns once the request is accepted, not when the workflow has finished reacting to it.
* Workflows that want to perform cleanup on cancel must use `workflow.NewDisconnectedContext` for the cleanup activities; otherwise those activities inherit the already-canceled context and exit immediately.
* To forcibly stop a workflow without giving it a chance to clean up, a termination API (not exposed here) would be required. Prefer cancellation whenever possible.
* Both `workflowID` and `workflowRunID` are required; the run ID ensures that a specific execution is targeted rather than the latest run of a given workflow ID.
* To confirm the cancellation took effect, poll `checkWorkflowStatus` or `workflowExecutions` until the status reaches `CANCELED`.

## Related

* Input: [CancelWorkflowInput](/graphql-api/inputs/cancelworkflowinput)
* Mutation: [checkWorkflowStatus](/graphql-api/mutations/checkworkflowstatus)
* Query: [workflowExecutions](/graphql-api/queries/workflowexecutions)

## Service

This mutation is defined in the **workflow** service.


# Check Workflow Status

checkWorkflowStatus Mutation

Checks the status of a running workflow instance in the Temporal workflow engine.

## Arguments

| Name    | Type                        | Description                                 |
| ------- | --------------------------- | ------------------------------------------- |
| `input` | `CheckWorkflowStatusInput!` | Input data for checking the workflow status |

## Return Type

`CheckWorkflowStatusResponse` - Contains the status information for the requested workflow.

## Input Fields

`CheckWorkflowStatusInput`:

| Field   | Type      | Description                                  |
| ------- | --------- | -------------------------------------------- |
| `id`    | `String!` | Required workflow ID to check status for     |
| `runID` | `String!` | Required workflow run ID to check status for |

## Return Fields

`CheckWorkflowStatusResponse`:

| Field      | Type               | Description                                                                         |
| ---------- | ------------------ | ----------------------------------------------------------------------------------- |
| `status`   | `String!`          | Current status of the workflow (e.g., "RUNNING", "COMPLETED", "FAILED", "CANCELED") |
| `workflow` | `TemporalWorkflow` | Workflow instance details if available                                              |

## Usage Example

```graphql
mutation {
  checkWorkflowStatus(
    input: {
      id: "inventory-restock-workflow-123",
      runID: "abc123de-f456-7890-ghij-klmnopqrstuv"
    }
  ) {
    status
    workflow {
      id
      runID
      status
      type
      startedAt
      completedAt
      result
      failure
    }
  }
}
```

## JavaScript Example

```javascript
const CHECK_WORKFLOW_STATUS = gql`
  mutation CheckWorkflowStatus($input: CheckWorkflowStatusInput!) {
    checkWorkflowStatus(input: $input) {
      status
      workflow {
        id
        runID
        status
        type
        startedAt
        completedAt
        result
        failure
      }
    }
  }
`;

const { data } = await client.mutate({
  mutation: CHECK_WORKFLOW_STATUS,
  variables: {
    input: {
      id: "inventory-restock-workflow-123",
      runID: "abc123de-f456-7890-ghij-klmnopqrstuv"
    }
  }
});

console.log(`Workflow status: ${data.checkWorkflowStatus.status}`);
if (data.checkWorkflowStatus.workflow) {
  console.log(`Workflow type: ${data.checkWorkflowStatus.workflow.type}`);
  console.log(`Started at: ${data.checkWorkflowStatus.workflow.startedAt}`);
}
```

## Possible Status Values

* **RUNNING**: The workflow is currently executing
* **COMPLETED**: The workflow has completed successfully
* **FAILED**: The workflow has failed with an error
* **CANCELED**: The workflow was canceled
* **TERMINATED**: The workflow was terminated
* **CONTINUED\_AS\_NEW**: The workflow continued as a new execution
* **TIMED\_OUT**: The workflow timed out

## Important Notes

* This mutation queries the Temporal workflow engine for real-time status
* Both `id` and `runID` are required to uniquely identify the workflow instance
* The workflow instance must exist in the Temporal cluster for the query to succeed
* Use this mutation to monitor long-running workflow executions
* Status information includes execution details, results, and failure information if applicable
* This is a read operation despite being a mutation (following GraphQL conventions for operations that might have side effects)


# Create Customer

Create Customer Mutation

Creates a new customer entity in the system.

## Arguments

| Name    | Type                   | Description                          |
| ------- | ---------------------- | ------------------------------------ |
| `input` | `CreateCustomerInput!` | Input data for creating the customer |

## Return Type

`Customer` - The created customer object.

## Input Fields

`CreateCustomerInput`:

| Field          | Type     | Description                  |
| -------------- | -------- | ---------------------------- |
| `dataTypeID`   | `UUID`   | Optional data type ID        |
| `dataTypeSlug` | `String` | Optional data type slug      |
| `data`         | `Map`    | Custom data for the customer |

## Usage Example

```graphql
mutation {
  createCustomer(
    input: {
      dataTypeSlug: "retail_customer",
      data: {
        "name": "John Smith",
        "email": "john.smith@example.com",
        "phone": "+1-555-0123",
        "address": {
          "street": "123 Main Street",
          "city": "New York",
          "state": "NY",
          "zip": "10001",
          "country": "USA"
        },
        "customerType": "individual",
        "preferredLanguage": "en",
        "marketingOptIn": true,
        "loyaltyNumber": "CUST-12345",
        "creditLimit": 5000.00,
        "paymentTerms": "NET15"
      }
    }
  ) {
    id
    dataTypeSlug
    data
    createdAt
  }
}
```

```graphql
mutation {
  # Create a business customer
  createCustomer(
    input: {
      dataTypeSlug: "business_customer",
      data: {
        "companyName": "Tech Solutions Inc.",
        "contactName": "Jane Doe",
        "email": "jane.doe@techsolutions.com",
        "phone": "+1-555-0456",
        "taxId": "12-3456789",
        "address": {
          "street": "456 Business Ave",
          "city": "San Francisco",
          "state": "CA",
          "zip": "94105",
          "country": "USA"
        },
        "accountManager": "Alice Johnson",
        "contractNumber": "CONT-2024-001",
        "creditLimit": 50000.00,
        "paymentTerms": "NET30",
        "industryType": "technology"
      }
    }
  ) {
    id
    data
  }
}
```

## Common Data Fields

While the `data` field is flexible, common customer attributes include:

* `name` - Customer name (individual or company)
* `email` - Primary contact email
* `phone` - Contact phone number
* `address` - Customer address object
* `customerType` - Type of customer (individual, business, etc.)
* `creditLimit` - Maximum credit allowed
* `paymentTerms` - Payment terms (NET15, NET30, etc.)
* `loyaltyNumber` - Customer loyalty program number
* `taxId` - Tax identification number (for business customers)
* `preferredLanguage` - Customer's preferred language
* `marketingOptIn` - Marketing communication consent

## Notes

* The `data` field is completely flexible for custom attributes
* Use `dataTypeSlug` to categorize customers (retail, wholesale, VIP, etc.)
* Customer email addresses should be unique within your system
* Consider setting up customer-specific pricing rules after creation


# Create Data Type

createDataType Mutation

Creates a new DataType definition in the system.

## Arguments

| Name    | Type                   | Description                           |
| ------- | ---------------------- | ------------------------------------- |
| `input` | `CreateDataTypeInput!` | Input data for creating the data type |

## Return Type

`DataType` - The created data type.

## Input Fields

`CreateDataTypeInput`:

| Field            | Type      | Description                                                                            |
| ---------------- | --------- | -------------------------------------------------------------------------------------- |
| `name`           | `String`  | Human-readable name of the data type                                                   |
| `slug`           | `String`  | Machine-readable slug used to reference the data type                                  |
| `description`    | `String`  | Description of the data type and its purpose                                           |
| `jsonSchema`     | `String!` | Required JSON Schema definition (as a string) that describes the structure of the data |
| `frontendSchema` | `String`  | Optional frontend-specific schema information (e.g., UI form definitions)              |
| `default`        | `Boolean` | Whether this is the default data type for its entity                                   |
| `entity`         | `String!` | Required entity type this data type is associated with (e.g., "customer", "item")      |

## Usage Example

```graphql
mutation {
  createDataType(
    input: {
      name: "Premium Product",
      slug: "premium_product",
      description: "Schema for premium products with extended attributes",
      entity: "item",
      default: false,
      jsonSchema: "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"premium_features\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"warranty_period\":{\"type\":\"integer\"},\"warranty_unit\":{\"type\":\"string\",\"enum\":[\"days\",\"months\",\"years\"]}},\"required\":[\"name\",\"premium_features\",\"warranty_period\",\"warranty_unit\"]}"
    }
  ) {
    id
    name
    slug
    description
    entity
    default
    jsonSchema
  }
}
```

This mutation creates a data type definition that can be used to structure and validate data for items in the system. The JSON Schema provided defines the expected structure, property types, and required fields for the entity's data.


# Create File

createFile Mutation

Creates a new File object.

## Arguments

| Name    | Type               | Description                      |
| ------- | ------------------ | -------------------------------- |
| `input` | `CreateFileInput!` | Input data for creating the file |

## Return Type

`CreateFileResult` - Contains the created file ID, the file object, and a pre-signed upload URL for the file content.

## Input Fields

`CreateFileInput`:

| Field          | Type           | Description                                                                                                                                                                                                                                                       |
| -------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dataTypeID`   | `UUID`         | Optional data type ID                                                                                                                                                                                                                                             |
| `dataTypeSlug` | `String`       | Optional data type slug                                                                                                                                                                                                                                           |
| `data`         | `Map`          | Custom data associated with the file                                                                                                                                                                                                                              |
| `refid`        | `UUID!`        | Required reference ID                                                                                                                                                                                                                                             |
| `reftype`      | `FileReftype!` | Required reference type                                                                                                                                                                                                                                           |
| `description`  | `String`       | Optional description                                                                                                                                                                                                                                              |
| `filename`     | `String!`      | Required filename                                                                                                                                                                                                                                                 |
| `size`         | `Int`          | Optional file size in bytes. Workers and clients that do not know the size up front can omit this field and call [`finalizeFileUpload`](/graphql-api/mutations/finalize-file-upload) after the bytes have been uploaded to S3 to populate it from object storage. |
| `contentType`  | `String!`      | Required content MIME type                                                                                                                                                                                                                                        |
| `publicAlias`  | `String`       | Optional human-readable, slug-based identifier (unique per tenant)                                                                                                                                                                                                |

{% hint style="warning" %}
**Breaking change:** `CreateFileInput.size` was changed from `Int!` to `Int`. The corresponding `File.size` field on the response type is now nullable as well. Existing clients must handle a missing `size` until [`finalizeFileUpload`](/graphql-api/mutations/finalize-file-upload) has been called.
{% endhint %}

## Recommended Upload Workflow

The typical pyck file upload flow is now a two-phase write:

1. Call `createFile` to create the metadata record. `size` may be omitted.
2. `PUT` the file bytes to the returned `preSignedUploadUrl`.
3. Call [`finalizeFileUpload`](/graphql-api/mutations/finalize-file-upload) with the file `id`. The resolver inspects the object in S3, reads its real byte size, and persists it on the `File` record.

This split lets workers and background pipelines record file metadata before the payload is available, then reconcile the size once the upload completes.

## Usage Example

```graphql
mutation {
  createFile(
    input: {
      refid: "550e8400-e29b-41d4-a716-446655440000"
      reftype: item
      filename: "product_image.jpg"
      contentType: "image/jpeg"
      description: "Product image for item"
      publicAlias: "product-image-smartphone-front"
    }
  ) {
    id
    preSignedUploadUrl
    file {
      id
      filename
      contentType
      size
      publicAlias
      publicURL
    }
  }
}
```

You may still pass `size` if it is known at creation time:

```graphql
mutation {
  createFile(
    input: {
      refid: "550e8400-e29b-41d4-a716-446655440000"
      reftype: item
      filename: "product_image.jpg"
      size: 12345
      contentType: "image/jpeg"
    }
  ) {
    id
    preSignedUploadUrl
  }
}
```

## Related

* [`finalizeFileUpload`](/graphql-api/mutations/finalize-file-upload) - Finalize the upload by persisting the real size from S3
* [File](/graphql-api/types/file) - File type reference


# Create Inventory Collection Movement

createInventoryCollectionMovement Mutation

Creates a collection of related item movements as a single operation in the inventory system.

## Arguments

| Name    | Type                             | Description                                         |
| ------- | -------------------------------- | --------------------------------------------------- |
| `input` | `CreateCollectionMovementInput!` | Input data for creating the collection of movements |

## Return Type

`CreateCollectionMovementOutput` - Contains the ID of the created collection, the list of movements, and associated workflow information.

### Output Fields

| Field       | Type                   | Description                                    |
| ----------- | ---------------------- | ---------------------------------------------- |
| `id`        | `ID!`                  | Unique identifier for the created collection   |
| `movements` | `[CollectionMovement]` | List of movements created in this collection   |
| `workflows` | `[TemporalWorkflow]`   | Workflow instances triggered by this operation |

## Input Fields

`CreateCollectionMovementInput`:

| Field          | Type                             | Description                                      |
| -------------- | -------------------------------- | ------------------------------------------------ |
| `dataTypeID`   | `UUID`                           | Optional data type ID for the collection         |
| `dataTypeSlug` | `String`                         | Optional data type slug for the collection       |
| `data`         | `Map`                            | Custom data associated with the collection       |
| `collection`   | `[CollectionMovementArrayInput]` | Required array of movement operations to perform |
| `handler`      | `String`                         | Handler for the collection movement              |

`CollectionMovementArrayInput`:

| Field          | Type      | Description                                               |
| -------------- | --------- | --------------------------------------------------------- |
| `handler`      | `String!` | Required handler for this specific movement               |
| `dataTypeID`   | `UUID`    | Optional data type ID for this movement                   |
| `dataTypeSlug` | `String`  | Optional data type slug for this movement                 |
| `data`         | `Map`     | Custom data for this movement                             |
| `fromID`       | `ID!`     | Required source repository ID                             |
| `toID`         | `ID!`     | Required destination repository ID                        |
| `itemID`       | `ID`      | Optional item ID (if applicable)                          |
| `quantity`     | `Float`   | Optional quantity (if applicable)                         |
| `repositoryID` | `ID`      | Optional repository ID for repository-specific operations |
| `orderID`      | `ID`      | Optional order ID for order-related movements             |

## Usage Example

```graphql
mutation {
  createInventoryCollectionMovement(
    input: {
      handler: "order_fulfillment",
      data: {
        "order_reference": "ORD-12345",
        "customer_id": "cust-456",
        "priority": "high"
      },
      collection: [
        {
          handler: "pick",
          fromID: "warehouse-main",
          toID: "packing-station-1",
          itemID: "item-123",
          quantity: 2,
          data: {
            "bin_location": "A1-B2"
          }
        },
        {
          handler: "pick",
          fromID: "warehouse-main",
          toID: "packing-station-1",
          itemID: "item-456",
          quantity: 3,
          data: {
            "bin_location": "C3-D4"
          }
        },
        {
          handler: "pack",
          fromID: "packing-station-1",
          toID: "shipping-area",
          data: {
            "package_type": "box",
            "package_dimensions": "30x20x15"
          }
        }
      ]
    }
  ) {
    id
    movements {
      id
      movementType
    }
    workflows {
      id
      runID
      type
    }
  }
}
```


# Create Inventory Item

Create Inventory Item Mutation

Creates a new InventoryItem object in the system.

## Arguments

| Name    | Type                        | Description                                |
| ------- | --------------------------- | ------------------------------------------ |
| `input` | `CreateInventoryItemInput!` | Input data for creating the inventory item |

## Return Type

`InventoryItemOutput` - Contains the created inventory item and any related workflows.

## Input Fields

`CreateInventoryItemInput`:

| Field                 | Type      | Description                                                        |
| --------------------- | --------- | ------------------------------------------------------------------ |
| `dataTypeID`          | `UUID`    | Optional data type ID                                              |
| `dataTypeSlug`        | `String`  | Optional data type slug                                            |
| `data`                | `Map`     | Custom data associated with the item                               |
| `sku`                 | `String!` | Required stock keeping unit (SKU) - unique identifier for the item |
| `inventoryJSONData`   | `Map`     | Additional inventory-specific JSON data                            |
| `itemmovementitemIDs` | `[ID!]`   | Optional IDs of item movements to associate                        |
| `itemtransactionIDs`  | `[ID!]`   | Optional IDs of transactions to associate                          |
| `itemstockIDs`        | `[ID!]`   | Optional IDs of stock records to associate                         |
| `itemsetIDs`          | `[ID!]`   | Optional IDs of item sets to associate                             |

## Usage Example

```graphql
mutation {
  createInventoryItem(
    input: {
      sku: "PRODUCT-123",
      dataTypeSlug: "electronic_device",
      data: {
        "name": "Smartphone X",
        "brand": "TechCorp",
        "model": "X100",
        "description": "Latest smartphone with advanced features",
        "specifications": {
          "display": "6.5 inch OLED",
          "processor": "Octa-core",
          "memory": "8GB",
          "storage": "256GB",
          "camera": "48MP"
        },
        "color": "black",
        "weight": 180
      }
    }
  ) {
    inventoryItem {
      id
      sku
      data
    }
    workflows {
      type
      id
      runID
    }
  }
}
```


# Create Inventory Item Movement

Create Inventory Item Movement Mutation

Creates a new item movement order to transfer inventory between repositories.

## Arguments

| Name    | Type                                | Description                          |
| ------- | ----------------------------------- | ------------------------------------ |
| `input` | `CreateInventoryItemMovementInput!` | Input data for creating the movement |

## Return Type

`InventoryItemMovementOutput` - Contains the created movement and any triggered workflows.

| Field          | Type                 | Description                               |
| -------------- | -------------------- | ----------------------------------------- |
| `itemMovement` | `ItemMovement!`      | The created item movement                 |
| `workflows`    | `[TemporalWorkflow]` | Any workflows triggered by this operation |

## Input Fields

`CreateInventoryItemMovementInput`:

| Field              | Type     | Description                     |
| ------------------ | -------- | ------------------------------- |
| `fromRepositoryID` | `UUID!`  | Source repository ID            |
| `toRepositoryID`   | `UUID!`  | Destination repository ID       |
| `itemID`           | `UUID!`  | ID of the item to move          |
| `quantity`         | `Int!`   | Quantity to move                |
| `dataTypeID`       | `UUID`   | Optional data type ID           |
| `dataTypeSlug`     | `String` | Optional data type slug         |
| `data`             | `Map`    | Custom data for the movement    |
| `collectionID`     | `UUID`   | Optional collection movement ID |

## Usage Example

```graphql
mutation {
  # Create a simple item movement
  createInventoryItemMovement(
    input: {
      fromRepositoryID: "shelf-a1",
      toRepositoryID: "packing-station-1",
      itemID: "item-123",
      quantity: 10,
      data: {
        "reason": "Order fulfillment",
        "orderRef": "ORD-2024-001"
      }
    }
  ) {
    itemMovement {
      id
      quantity
      fromRepository {
        name
      }
      toRepository {
        name
      }
      item {
        sku
      }
      blockedBy
    }
  }
}
```

```graphql
mutation {
  # Create movement as part of a collection
  createInventoryItemMovement(
    input: {
      fromRepositoryID: "warehouse-bulk",
      toRepositoryID: "pick-face-a1",
      itemID: "item-789",
      quantity: 50,
      collectionID: "collection-456",
      dataTypeSlug: "replenishment_movement",
      data: {
        "priority": "high",
        "triggerLevel": 10
      }
    }
  ) {
    itemMovement {
      id
      quantity
      collectionID
    }
    workflows {
      id
      type
      runID
      status
      startedAt
      completedAt
    }
  }
}
```

## Notes

* Movement validates stock availability (unless from virtual repository)
* Created in pending state - use `executeInventoryItemMovement` to execute
* Can be part of a collection for coordinated execution
* May be blocked if insufficient stock or business rules prevent it


# Create Inventory Item Set

Create Inventory Item Set Mutation

Creates a new InventoryItemSet object in the system. Item sets represent logical groupings of related inventory items, such as product bundles, kits, or collections that are managed together.

## Arguments

| Name    | Type                           | Description                                        |
| ------- | ------------------------------ | -------------------------------------------------- |
| `input` | `CreateInventoryItemSetInput!` | Input data for creating the new inventory item set |

## Return Type

`InventoryItemSetOutput` - Contains the created inventory item set and any related workflows.

## Input Fields

`CreateInventoryItemSetInput`:

| Field          | Type      | Description                                           |
| -------------- | --------- | ----------------------------------------------------- |
| `dataTypeID`   | `UUID`    | Optional data type ID to associate with the item set  |
| `dataTypeSlug` | `String`  | Optional data type slug for categorization            |
| `data`         | `Map`     | Custom data associated with the item set              |
| `sku`          | `String!` | **Required** - Unique SKU identifier for the item set |
| `itemIDs`      | `[ID!]`   | List of inventory item IDs to include in this set     |

## Return Fields

`InventoryItemSetOutput`:

| Field              | Type                 | Description                                            |
| ------------------ | -------------------- | ------------------------------------------------------ |
| `inventoryItemSet` | `InventoryItemSet`   | The created inventory item set                         |
| `workflows`        | `[TemporalWorkflow]` | Workflow instances that were triggered by the creation |

## Usage Example

```graphql
mutation {
  createInventoryItemSet(input: {
    sku: "STARTER_KIT_001",
    data: {
      "name": "Warehouse Starter Kit",
      "description": "Essential items for new warehouse operations",
      "category": "operational_kit",
      "bundle_type": "starter_package",
      "total_value": 2500.00,
      "weight_kg": 45.2,
      "contains_hazardous": false,
      "assembly_required": true,
      "supplier": "WareHouse Solutions Inc",
      "warranty_months": 12,
      "instructions_url": "https://docs.example.com/starter-kit"
    },
    dataTypeSlug: "operational_kit",
    itemIDs: [
      "scanner_001",
      "printer_thermal_002", 
      "cart_mobile_003",
      "supplies_basic_004",
      "tablet_android_005"
    ]
  }) {
    inventoryItemSet {
      id
      sku
      data
      dataTypeSlug
      items {
        id
        sku
        inventoryJSONData
      }
      createdAt
      createdBy
    }
    workflows {
      id
      type
      status
      runID
      startedAt
      completedAt
    }
  }
}
```

## JavaScript Example

```javascript
const CREATE_INVENTORY_ITEM_SET = gql`
  mutation CreateInventoryItemSet($input: CreateInventoryItemSetInput!) {
    createInventoryItemSet(input: $input) {
      inventoryItemSet {
        id
        sku
        data
        dataTypeSlug
        items {
          id
          sku
          inventoryJSONData
        }
        createdAt
        createdBy
      }
      workflows {
        id
        type
        status
        runID
        startedAt
        completedAt
      }
    }
  }
`;

const { data } = await client.mutate({
  mutation: CREATE_INVENTORY_ITEM_SET,
  variables: {
    input: {
      sku: "STARTER_KIT_001",
      data: {
        name: "Warehouse Starter Kit",
        description: "Essential items for new warehouse operations",
        category: "operational_kit",
        bundle_type: "starter_package",
        total_value: 2500.00,
        weight_kg: 45.2,
        contains_hazardous: false,
        assembly_required: true,
        supplier: "WareHouse Solutions Inc",
        warranty_months: 12,
        instructions_url: "https://docs.example.com/starter-kit"
      },
      dataTypeSlug: "operational_kit",
      itemIDs: [
        "scanner_001",
        "printer_thermal_002", 
        "cart_mobile_003",
        "supplies_basic_004",
        "tablet_android_005"
      ]
    }
  }
});

console.log(`Created item set: ${data.createInventoryItemSet.inventoryItemSet.sku}`);
```

## Important Notes

* **SKU Uniqueness**: The SKU must be unique across all inventory item sets in the system
* **Item Validation**: All items referenced in `itemIDs` must exist and be accessible
* **Workflow Triggers**: Creating an item set may trigger workflows for bundle management, pricing updates, or inventory synchronization
* **Data Integrity**: The system validates that all referenced items are valid and accessible
* **Authorization**: Ensure you have proper permissions to create item sets and reference the specified items
* **Relationship Management**: The system automatically creates bidirectional relationships between the set and its items

## Common Use Cases

1. **Product Bundles**: Group related products sold together (e.g., starter kits, combo packages)
2. **Maintenance Kits**: Collections of spare parts and tools for equipment maintenance
3. **Seasonal Collections**: Items grouped for seasonal sales or promotions
4. **Assembly Sets**: Components that combine to create a finished product
5. **Replacement Kits**: Collections of commonly replaced parts
6. **Training Sets**: Items used together for training or demonstration purposes

## Best Practices

* **Meaningful SKUs**: Use descriptive SKU patterns that indicate the set's purpose
* **Complete Data**: Include comprehensive metadata in the `data` field for better management
* **Logical Grouping**: Ensure items in the set have a logical business relationship
* **Documentation**: Include assembly instructions, usage notes, or related documentation URLs
* **Validation**: Verify all component items exist before creating the set

## Related Operations

After creating an inventory item set, you may need to:

* Create stock records for the item set in appropriate repositories
* Set up pricing rules for bundle discounts
* Configure movement rules for keeping sets together
* Update catalog systems with the new item set
* Create workflow rules for set assembly or disassembly

## Error Handling

Common errors when creating item sets:

* **Duplicate SKU**: The specified SKU already exists
* **Invalid Item References**: One or more items in `itemIDs` don't exist or aren't accessible
* **Insufficient Permissions**: User lacks permission to create item sets or reference specific items
* **Data Validation**: Custom data doesn't meet schema requirements


# Create Inventory Repository

createInventoryRepository Mutation

Creates a new Repository in the inventory system.

## Arguments

| Name    | Type                     | Description                            |
| ------- | ------------------------ | -------------------------------------- |
| `input` | `CreateRepositoryInput!` | Input data for creating the repository |

## Return Type

`InventoryRepositoryOutput` - Contains the created repository and any associated workflows.

## Input Fields

`CreateRepositoryInput`:

| Field                                 | Type              | Description                                                                |
| ------------------------------------- | ----------------- | -------------------------------------------------------------------------- |
| `dataTypeID`                          | `UUID`            | Optional data type ID                                                      |
| `dataTypeSlug`                        | `String`          | Optional data type slug                                                    |
| `data`                                | `Map`             | Custom data associated with the repository                                 |
| `locationID`                          | `UUID`            | Optional location ID                                                       |
| `name`                                | `String!`         | Required name of the repository                                            |
| `layout`                              | `String`          | Optional layout information for the repository                             |
| `type`                                | `RepositoryType!` | Required type of the repository (dynamic or static)                        |
| `virtualRepo`                         | `Boolean`         | Whether this is a virtual repository (non-physical location)               |
| `parentID`                            | `ID`              | Optional parent repository ID (edge reference) for hierarchical structures |
| `childIDs`                            | `[ID!]`           | Optional array of child repository IDs to associate                        |
| `itemmovementtorepositoryIDs`         | `[ID!]`           | Optional item movement IDs (incoming)                                      |
| `itemmovementfromrepositoryIDs`       | `[ID!]`           | Optional item movement IDs (outgoing)                                      |
| `repositorymovementtorepositoryIDs`   | `[ID!]`           | Optional repository movement IDs (incoming)                                |
| `repositorymovementfromrepositoryIDs` | `[ID!]`           | Optional repository movement IDs (outgoing)                                |
| `repositorymovementrepositoryIDs`     | `[ID!]`           | Optional repository movement IDs                                           |
| `repositorytransactionIDs`            | `[ID!]`           | Optional transaction IDs                                                   |
| `repositorystockIDs`                  | `[ID!]`           | Optional stock IDs                                                         |

## Breaking Changes

The `parentID` field type has changed from `UUID` to `ID`. This is an edge reference field that establishes a parent-child relationship between repositories. If you were previously passing a UUID string, you should now pass the repository's GraphQL ID.

Additionally, a new `childIDs` field has been added to allow specifying child repositories during creation.

## Usage Example

```graphql
mutation {
  createInventoryRepository(
    input: {
      name: "North Warehouse",
      type: static,
      virtualRepo: false,
      data: {
        "address": {
          "street": "123 Industrial Blvd",
          "city": "Springfield",
          "postalCode": "12345",
          "country": "US"
        },
        "manager": "John Smith",
        "contactPhone": "+1-555-123-4567",
        "operatingHours": "8:00 AM - 5:00 PM"
      }
    }
  ) {
    inventoryRepository {
      id
      name
      type
      virtualRepo
      data
    }
    workflows {
      type
      id
      runID
      status
    }
  }
}
```

### Create a Child Repository

```graphql
mutation {
  # Create a child repository (shelf in a warehouse)
  createInventoryRepository(
    input: {
      name: "Shelf A1",
      type: static,
      parentID: "550e8400-e29b-41d4-a716-446655440000",
      virtualRepo: false,
      layout: "North Wall"
    }
  ) {
    inventoryRepository {
      id
      name
      type
      parentID
      parent {
        id
        name
      }
    }
  }
}
```

### Create Repository with Children

```graphql
mutation {
  # Create a repository and assign existing children
  createInventoryRepository(
    input: {
      name: "Zone A",
      type: static,
      virtualRepo: false,
      childIDs: [
        "shelf-1-id",
        "shelf-2-id"
      ]
    }
  ) {
    inventoryRepository {
      id
      name
      children {
        id
        name
      }
    }
  }
}
```


# Create Inventory Repository Movement

Create Inventory Repository Movement Mutation

Creates a new repository movement order to relocate a dynamic repository (like a pallet or tote) from one location to another.

## Arguments

| Name    | Type                             | Description                                     |
| ------- | -------------------------------- | ----------------------------------------------- |
| `input` | `CreateRepositoryMovementInput!` | Input data for creating the repository movement |

## Return Type

`InventoryRepositoryMovementOutput` - Contains the created repository movement and any triggered workflows.

| Field                         | Type                 | Description                               |
| ----------------------------- | -------------------- | ----------------------------------------- |
| `inventoryRepositoryMovement` | `RepositoryMovement` | The created repository movement           |
| `workflows`                   | `[TemporalWorkflow]` | Any workflows triggered by this operation |

## Input Fields

`CreateRepositoryMovementInput`:

| Field          | Type                          | Description                                     |
| -------------- | ----------------------------- | ----------------------------------------------- |
| `dataTypeID`   | `UUID`                        | Optional data type ID                           |
| `dataTypeSlug` | `String`                      | Optional data type slug                         |
| `data`         | `Map`                         | Custom data for the movement                    |
| `executed`     | `Boolean`                     | Whether to execute immediately (default: false) |
| `handler`      | `String!`                     | Handler responsible for the movement            |
| `blockedBy`    | `RepositoryMovementBlockedBy` | Blocking reason if applicable                   |
| `collectionID` | `UUID`                        | Optional collection movement ID                 |
| `orderID`      | `UUID`                        | Optional associated order ID                    |
| `position`     | `Int`                         | Position in execution order                     |
| `fromID`       | `ID`                          | Source repository ID (parent location)          |
| `toID`         | `ID!`                         | Destination repository ID (parent location)     |
| `repositoryID` | `ID!`                         | ID of the repository to move                    |

## Usage Example

```graphql
mutation {
  # Move a pallet from one zone to another
  createInventoryRepositoryMovement(
    input: {
      repositoryID: "pallet-123",
      fromID: "zone-receiving",
      toID: "zone-storage-a",
      handler: "forklift-operator-01",
      data: {
        "reason": "Storage optimization",
        "priority": "normal"
      }
    }
  ) {
    inventoryRepositoryMovement {
      id
      repository {
        name
        type
      }
      from {
        name
      }
      to {
        name
      }
      executed
      handler
    }
  }
}
```

```graphql
mutation {
  # Create movement as part of a collection
  createInventoryRepositoryMovement(
    input: {
      repositoryID: "tote-456",
      fromID: "staging-area",
      toID: "shipping-dock",
      handler: "system",
      collectionID: "collection-789",
      position: 1,
      dataTypeSlug: "shipping_preparation"
    }
  ) {
    inventoryRepositoryMovement {
      id
      collectionID
      position
    }
    workflows {
      id
      type
      runID
      status
      startedAt
      completedAt
    }
  }
}
```

## Notes

* Repository movements relocate dynamic repositories (containers) within the warehouse
* The `repositoryID` is the container being moved (pallet, tote, trolley)
* The `fromID` and `toID` are the parent locations (zones, areas, docks)
* Created in pending state - use `executeInventoryRepositoryMovement` to execute
* Can be part of a collection for coordinated execution
* May be blocked for safety or compliance reasons


# Create Picking Order

createPickingOrder Mutation

Creates a new PickingOrder with associated order items.

## Arguments

| Name    | Type                                | Description                                             |
| ------- | ----------------------------------- | ------------------------------------------------------- |
| `input` | `CreatePickingOrderWithItemsInput!` | Input data for creating the picking order and its items |

## Return Type

`PickingOrderOutput` - Contains the created picking order and any associated workflows.

## Input Fields

`CreatePickingOrderWithItemsInput`:

| Field          | Type                             | Description                                   |
| -------------- | -------------------------------- | --------------------------------------------- |
| `dataTypeID`   | `UUID`                           | Optional data type ID                         |
| `dataTypeSlug` | `String`                         | Optional data type slug                       |
| `data`         | `Map`                            | Custom data associated with the picking order |
| `customerID`   | `UUID`                           | ID of the customer this order is for          |
| `orderItems`   | `[CreatePickingOrderItemsInput]` | List of order items to create with this order |

`CreatePickingOrderItemsInput`:

| Field          | Type      | Description                                   |
| -------------- | --------- | --------------------------------------------- |
| `dataTypeID`   | `UUID`    | Optional data type ID                         |
| `dataTypeSlug` | `String`  | Optional data type slug                       |
| `data`         | `Map`     | Custom data associated with the order item    |
| `sku`          | `String!` | Required stock keeping unit (SKU) of the item |
| `quantity`     | `Int!`    | Required quantity of the item                 |

## Usage Example

```graphql
mutation {
  createPickingOrder(
    input: {
      customerID: "550e8400-e29b-41d4-a716-446655440000",
      data: {
        "order_number": "PO-12345",
        "priority": "high",
        "delivery_address": {
          "street": "123 Main St",
          "city": "Springfield",
          "postalCode": "12345",
          "country": "US"
        },
        "notes": "Handle with care"
      },
      orderItems: [
        {
          sku: "ITEM-123",
          quantity: 5,
          data: {
            "notes": "Gift wrapped"
          }
        },
        {
          sku: "ITEM-456",
          quantity: 2
        }
      ]
    }
  ) {
    pickingOrder {
      id
      customerID
      data
      orderitems {
        id
        sku
        quantity
        data
      }
    }
    workflows {
      id
      type
      id
      runID
      status
    }
  }
}
```


# Create Picking Order Item

createPickingOrderItem Mutation

Creates a new picking order item and associates it with an existing picking order. This allows adding individual items to a picking order after it has been created.

## Arguments

| Name    | Type                           | Description                                    |
| ------- | ------------------------------ | ---------------------------------------------- |
| `input` | `CreatePickingOrderItemInput!` | Input data for creating the picking order item |

## Return Type

`PickingOrderItemOutput` - Contains the created picking order item and any associated workflows.

## Input Fields

`CreatePickingOrderItemInput`:

| Field          | Type      | Description                                                  |
| -------------- | --------- | ------------------------------------------------------------ |
| `dataTypeID`   | `UUID`    | Optional data type ID for custom validation                  |
| `dataTypeSlug` | `String`  | Optional data type slug for custom validation                |
| `data`         | `Map`     | Custom data associated with the order item                   |
| `sku`          | `String!` | Required stock keeping unit (SKU) of the item                |
| `quantity`     | `Int!`    | Required quantity of the item to pick                        |
| `orderID`      | `ID!`     | Required ID of the picking order to associate this item with |

## Usage Example

```graphql
mutation {
  createPickingOrderItem(
    input: {
      sku: "WIDGET-123",
      quantity: 10,
      orderID: "550e8400-e29b-41d4-a716-446655440000",
      data: {
        "priority": "high",
        "location_hint": "Aisle 5, Shelf B",
        "special_handling": "fragile"
      }
    }
  ) {
    pickingOrderItem {
      id
      sku
      quantity
      data
      createdAt
      order {
        id
        customerID
      }
    }
    workflows {
      id
      type
      id
      runID
      status
    }
  }
}
```

## JavaScript Example

```javascript
const createPickingOrderItemMutation = `
  mutation CreatePickingOrderItem($input: CreatePickingOrderItemInput!) {
    createPickingOrderItem(input: $input) {
      pickingOrderItem {
        id
        sku
        quantity
        data
        createdAt
        order {
          id
          customerID
        }
      }
      workflows {
        id
        type
        id
        runID
        status
      }
    }
  }
`;

const variables = {
  input: {
    sku: "WIDGET-123",
    quantity: 10,
    orderID: "550e8400-e29b-41d4-a716-446655440000",
    data: {
      priority: "high",
      location_hint: "Aisle 5, Shelf B",
      special_handling: "fragile"
    }
  }
};

// Using fetch or your preferred GraphQL client
const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({
    query: createPickingOrderItemMutation,
    variables: variables
  })
});

const result = await response.json();
console.log('Created picking order item:', result.data.createPickingOrderItem);
```

## Notes

* The specified `orderID` must exist and be accessible to the current user
* The `sku` should correspond to an existing inventory item
* The `quantity` must be a positive integer
* Custom `data` can include any JSON-serializable information relevant to the item
* Associated workflows may be automatically triggered based on system configuration
* The operation may fail if the picking order is already in a non-editable state


# Create Picking Outbound Shipment Notification

createPickingOutboundShipmentNotification Mutation

Audience: Programmer

Creates a new `PickingOutboundShipmentNotification` linked to an existing picking order. Outbound shipment notifications allow downstream consumers to react when an outbound shipment completes.

## Arguments

| Name    | Type                                              | Description                              |
| ------- | ------------------------------------------------- | ---------------------------------------- |
| `input` | `CreatePickingOutboundShipmentNotificationInput!` | Input data for creating the notification |

## Return Type

`PickingOutboundShipmentNotificationOutput` - Contains the created notification and any associated workflows.

## Input Fields

`CreatePickingOutboundShipmentNotificationInput`:

| Field          | Type     | Description                                        |
| -------------- | -------- | -------------------------------------------------- |
| `dataTypeID`   | `UUID`   | Optional data type ID for custom validation        |
| `dataTypeSlug` | `String` | Optional data type slug for custom validation      |
| `data`         | `Map`    | Custom JSONB data associated with the notification |
| `orderID`      | `ID!`    | Required ID of the parent picking order            |

## Response Fields

`PickingOutboundShipmentNotificationOutput`:

| Field                                 | Type                                  | Description                             |
| ------------------------------------- | ------------------------------------- | --------------------------------------- |
| `pickingOutboundShipmentNotification` | `PickingOutboundShipmentNotification` | The created notification                |
| `workflows`                           | `[TemporalWorkflow]`                  | Any workflows triggered by the creation |

## Usage Example

```graphql
mutation {
  createPickingOutboundShipmentNotification(
    input: {
      orderID: "550e8400-e29b-41d4-a716-446655440000",
      data: {
        "carrier": "DHL",
        "tracking_number": "TRK987654321",
        "shipped_at": "2026-04-10T10:30:00Z",
        "notes": "Express delivery"
      }
    }
  ) {
    pickingOutboundShipmentNotification {
      id
      tenantID
      orderID
      data
      createdAt
      createdBy
      order {
        id
        customerID
      }
    }
    workflows {
      id
      type
      runID
      status
    }
  }
}
```

## JavaScript Example

```javascript
const createMutation = `
  mutation CreatePickingOutboundShipmentNotification($input: CreatePickingOutboundShipmentNotificationInput!) {
    createPickingOutboundShipmentNotification(input: $input) {
      pickingOutboundShipmentNotification {
        id
        orderID
        data
        createdAt
      }
      workflows {
        id
        type
        runID
        status
      }
    }
  }
`;

const variables = {
  input: {
    orderID: "550e8400-e29b-41d4-a716-446655440000",
    data: {
      carrier: "DHL",
      tracking_number: "TRK987654321",
      shipped_at: "2026-04-10T10:30:00Z",
      notes: "Express delivery"
    }
  }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({ query: createMutation, variables })
});

const result = await response.json();
console.log('Created notification:', result.data.createPickingOutboundShipmentNotification);
```

## Notes

* The parent picking order referenced by `orderID` must exist and be accessible to the current user.
* The `data` field is validated against the data type schema if `dataTypeID` or `dataTypeSlug` is provided.
* Creating a notification may trigger Temporal workflows for downstream consumers; inspect the `workflows` field in the response to track them.


# Create Receiving Inbound

createReceivingInbound Mutation

Creates a new ReceivingInbound with associated inbound items.

## Arguments

| Name    | Type                                    | Description                                                |
| ------- | --------------------------------------- | ---------------------------------------------------------- |
| `input` | `CreateReceivingInboundWithItemsInput!` | Input data for creating the inbound shipment and its items |

## Return Type

`ReceivingInboundOutput` - Contains the created inbound shipment and any associated workflows.

## Input Fields

`CreateReceivingInboundWithItemsInput`:

| Field          | Type                                 | Description                                                |
| -------------- | ------------------------------------ | ---------------------------------------------------------- |
| `dataTypeID`   | `UUID`                               | Optional data type ID                                      |
| `dataTypeSlug` | `String`                             | Optional data type slug                                    |
| `data`         | `Map`                                | Custom data associated with the inbound shipment           |
| `supplierID`   | `UUID`                               | ID of the supplier this inbound is from                    |
| `orderID`      | `String`                             | Optional order or reference ID for the inbound shipment    |
| `inboundItems` | `[CreateReceivingInboundItemsInput]` | List of inbound items to create with this inbound shipment |

`CreateReceivingInboundItemsInput`:

| Field          | Type      | Description                                   |
| -------------- | --------- | --------------------------------------------- |
| `dataTypeID`   | `UUID`    | Optional data type ID                         |
| `dataTypeSlug` | `String`  | Optional data type slug                       |
| `data`         | `Map`     | Custom data associated with the inbound item  |
| `sku`          | `String!` | Required stock keeping unit (SKU) of the item |
| `quantity`     | `Int!`    | Required quantity of the item                 |

## Usage Example

```graphql
mutation {
  createReceivingInbound(
    input: {
      supplierID: "550e8400-e29b-41d4-a716-446655440000",
      orderID: "PO-98765",
      data: {
        "expected_arrival_date": "2023-06-15",
        "carrier": "Express Logistics",
        "tracking_number": "TRK123456789",
        "notes": "Requires inspection upon arrival"
      },
      inboundItems: [
        {
          sku: "ITEM-123",
          quantity: 50,
          data: {
            "batch_number": "BN-001",
            "expiry_date": "2025-12-31"
          }
        },
        {
          sku: "ITEM-456",
          quantity: 25
        }
      ]
    }
  ) {
    receivingInbound {
      id
      orderID
      supplierID
      data
      inbounditems {
        id
        sku
        quantity
        data
      }
    }
    workflows {
      id
      type
      id
      runID
      status
    }
  }
}
```


# Create Receiving Inbound Item

createReceivingInboundItem Mutation

Creates a new receiving inbound item and associates it with an existing receiving inbound order. This allows adding individual items to a receiving order after it has been created.

## Arguments

| Name    | Type                               | Description                                        |
| ------- | ---------------------------------- | -------------------------------------------------- |
| `input` | `CreateReceivingInboundItemInput!` | Input data for creating the receiving inbound item |

## Return Type

`ReceivingInboundItemOutput` - Contains the created receiving inbound item and any associated workflows.

## Input Fields

`CreateReceivingInboundItemInput`:

| Field          | Type      | Description                                                            |
| -------------- | --------- | ---------------------------------------------------------------------- |
| `dataTypeID`   | `UUID`    | Optional data type ID for custom validation                            |
| `dataTypeSlug` | `String`  | Optional data type slug for custom validation                          |
| `data`         | `Map`     | Custom data associated with the inbound item                           |
| `sku`          | `String!` | Required stock keeping unit (SKU) of the item                          |
| `quantity`     | `Int!`    | Required quantity of the item being received                           |
| `inboundID`    | `ID!`     | Required ID of the receiving inbound order to associate this item with |

## Usage Example

```graphql
mutation {
  createReceivingInboundItem(
    input: {
      sku: "COMPONENT-789",
      quantity: 25,
      inboundID: "550e8400-e29b-41d4-a716-446655440000",
      data: {
        "lot_number": "LOT-2024-001",
        "expiration_date": "2025-12-31",
        "condition": "new",
        "supplier_batch": "BATCH-456",
        "quality_check_required": true
      }
    }
  ) {
    receivingInboundItem {
      id
      sku
      quantity
      data
      createdAt
      inbound {
        id
        supplierID
        orderID
      }
    }
    workflows {
      id
      type
      id
      runID
      status
    }
  }
}
```

## JavaScript Example

```javascript
const createReceivingInboundItemMutation = `
  mutation CreateReceivingInboundItem($input: CreateReceivingInboundItemInput!) {
    createReceivingInboundItem(input: $input) {
      receivingInboundItem {
        id
        sku
        quantity
        data
        createdAt
        inbound {
          id
          supplierID
          orderID
        }
      }
      workflows {
        id
        type
        id
        runID
        status
      }
    }
  }
`;

const variables = {
  input: {
    sku: "COMPONENT-789",
    quantity: 25,
    inboundID: "550e8400-e29b-41d4-a716-446655440000",
    data: {
      lot_number: "LOT-2024-001",
      expiration_date: "2025-12-31",
      condition: "new",
      supplier_batch: "BATCH-456",
      quality_check_required: true
    }
  }
};

// Using fetch or your preferred GraphQL client
const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({
    query: createReceivingInboundItemMutation,
    variables: variables
  })
});

const result = await response.json();
console.log('Created receiving inbound item:', result.data.createReceivingInboundItem);
```

## Batch Creation Example

You can create multiple inbound items for the same order:

```javascript
const items = [
  {
    sku: "COMPONENT-789",
    quantity: 25,
    data: { lot_number: "LOT-2024-001", condition: "new" }
  },
  {
    sku: "COMPONENT-790",
    quantity: 50,
    data: { lot_number: "LOT-2024-002", condition: "new" }
  },
  {
    sku: "COMPONENT-791",
    quantity: 10,
    data: { lot_number: "LOT-2024-003", condition: "damaged", quality_check_required: true }
  }
];

const inboundID = "550e8400-e29b-41d4-a716-446655440000";

const createResults = await Promise.all(
  items.map(async (item) => {
    const response = await fetch('/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_TOKEN'
      },
      body: JSON.stringify({
        query: createReceivingInboundItemMutation,
        variables: {
          input: {
            ...item,
            inboundID
          }
        }
      })
    });
    
    const result = await response.json();
    return result.data.createReceivingInboundItem;
  })
);

console.log('Batch creation results:', createResults);
```

## Notes

* The specified `inboundID` must exist and be accessible to the current user
* The `sku` should correspond to an expected inventory item
* The `quantity` must be a positive integer
* Custom `data` can include tracking information like lot numbers, expiration dates, condition, etc.
* Associated workflows may be automatically triggered based on system configuration (e.g., quality checks, inventory updates)
* The operation may fail if the receiving inbound order is already in a non-editable state
* Consider including relevant receiving information in the `data` field for tracking and compliance
* This mutation is typically used in receiving workflows when items arrive in shipments


# Create Receiving Inbound Shipment Notification

createReceivingInboundShipmentNotification Mutation

Audience: Programmer

Creates a new `ReceivingInboundShipmentNotification` linked to an existing receiving inbound. Inbound shipment notifications allow downstream consumers to react when an inbound receipt completes.

## Arguments

| Name    | Type                                               | Description                              |
| ------- | -------------------------------------------------- | ---------------------------------------- |
| `input` | `CreateReceivingInboundShipmentNotificationInput!` | Input data for creating the notification |

## Return Type

`ReceivingInboundShipmentNotificationOutput` - Contains the created notification and any associated workflows.

## Input Fields

`CreateReceivingInboundShipmentNotificationInput`:

| Field          | Type     | Description                                        |
| -------------- | -------- | -------------------------------------------------- |
| `dataTypeID`   | `UUID`   | Optional data type ID for custom validation        |
| `dataTypeSlug` | `String` | Optional data type slug for custom validation      |
| `data`         | `Map`    | Custom JSONB data associated with the notification |
| `inboundID`    | `ID!`    | Required ID of the parent receiving inbound        |

## Response Fields

`ReceivingInboundShipmentNotificationOutput`:

| Field                                  | Type                                   | Description                             |
| -------------------------------------- | -------------------------------------- | --------------------------------------- |
| `receivingInboundShipmentNotification` | `ReceivingInboundShipmentNotification` | The created notification                |
| `workflows`                            | `[TemporalWorkflow]`                   | Any workflows triggered by the creation |

## Usage Example

```graphql
mutation {
  createReceivingInboundShipmentNotification(
    input: {
      inboundID: "550e8400-e29b-41d4-a716-446655440000",
      data: {
        "carrier": "Express Logistics",
        "tracking_number": "TRK123456789",
        "arrived_at": "2026-04-10T14:15:00Z",
        "dock_door": "D-07",
        "notes": "Inspection required"
      }
    }
  ) {
    receivingInboundShipmentNotification {
      id
      tenantID
      inboundID
      data
      createdAt
      createdBy
      inbound {
        id
        orderID
        supplierID
      }
    }
    workflows {
      id
      type
      runID
      status
    }
  }
}
```

## JavaScript Example

```javascript
const createMutation = `
  mutation CreateReceivingInboundShipmentNotification($input: CreateReceivingInboundShipmentNotificationInput!) {
    createReceivingInboundShipmentNotification(input: $input) {
      receivingInboundShipmentNotification {
        id
        inboundID
        data
        createdAt
      }
      workflows {
        id
        type
        runID
        status
      }
    }
  }
`;

const variables = {
  input: {
    inboundID: "550e8400-e29b-41d4-a716-446655440000",
    data: {
      carrier: "Express Logistics",
      tracking_number: "TRK123456789",
      arrived_at: "2026-04-10T14:15:00Z",
      dock_door: "D-07",
      notes: "Inspection required"
    }
  }
};

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify({ query: createMutation, variables })
});

const result = await response.json();
console.log('Created notification:', result.data.createReceivingInboundShipmentNotification);
```

## Notes

* The parent receiving inbound referenced by `inboundID` must exist and be accessible to the current user.
* The `data` field is validated against the data type schema if `dataTypeID` or `dataTypeSlug` is provided.
* Creating a notification may trigger Temporal workflows for downstream consumers; inspect the `workflows` field in the response to track them.


# Create Supplier

Create Supplier Mutation

Creates a new supplier entity in the system.

## Arguments

| Name    | Type                   | Description                          |
| ------- | ---------------------- | ------------------------------------ |
| `input` | `CreateSupplierInput!` | Input data for creating the supplier |

## Return Type

`Supplier` - The created supplier object.

## Input Fields

`CreateSupplierInput`:

| Field          | Type     | Description                  |
| -------------- | -------- | ---------------------------- |
| `dataTypeID`   | `UUID`   | Optional data type ID        |
| `dataTypeSlug` | `String` | Optional data type slug      |
| `data`         | `Map`    | Custom data for the supplier |

## Usage Example

```graphql
mutation {
  createSupplier(
    input: {
      dataTypeSlug: "domestic_supplier",
      data: {
        "name": "ACME Supply Co.",
        "code": "SUP-001",
        "email": "orders@acmesupply.com",
        "phone": "+1-555-0123",
        "address": {
          "street": "123 Industrial Way",
          "city": "Manufacturing City",
          "state": "CA",
          "zip": "90210",
          "country": "USA"
        },
        "contactPerson": "John Doe",
        "paymentTerms": "NET30",
        "leadTimeDays": 7,
        "minimumOrderValue": 500.00,
        "preferredDeliveryDays": ["Monday", "Wednesday", "Friday"],
        "certifications": ["ISO9001", "ISO14001"],
        "vendorRating": 4.5
      }
    }
  ) {
    id
    dataTypeSlug
    data
    createdAt
  }
}
```

```graphql
mutation {
  # Create an international supplier
  createSupplier(
    input: {
      dataTypeSlug: "international_supplier",
      data: {
        "name": "Global Components Ltd.",
        "code": "SUP-INT-001",
        "email": "sales@globalcomponents.com",
        "country": "China",
        "currency": "USD",
        "incoterms": "FOB",
        "leadTimeDays": 30,
        "minimumOrderQuantity": 1000,
        "paymentTerms": "LC",
        "customsClearanceRequired": true
      }
    }
  ) {
    id
    data
  }
}
```

## Common Data Fields

While the `data` field is flexible, common supplier attributes include:

* `name` - Supplier company name
* `code` - Unique supplier code
* `email` - Primary contact email
* `phone` - Contact phone number
* `address` - Supplier address object
* `contactPerson` - Primary contact name
* `paymentTerms` - Payment terms (NET30, COD, etc.)
* `leadTimeDays` - Standard lead time
* `minimumOrderValue` - Minimum order amount
* `certifications` - Quality certifications
* `vendorRating` - Supplier rating

## Notes

* The `data` field is completely flexible for custom attributes
* Use `dataTypeSlug` to categorize suppliers
* Consider creating virtual repositories named after suppliers for receiving
* Supplier codes should be unique within your system




---

[Next Page](https://docs.pyck.cloud/llms-full.txt/1)

