> For the complete documentation index, see [llms.txt](https://docs.pyck.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pyck.cloud/graphql-api/mutations/sendcustomevent.md).

# Send Custom Event

Send Custom Event Mutation

Audience: Programmer

Sends a custom event to the pyck event system for processing by workflows and external integrations. The mutation now returns information about any workflows that were triggered by the event.

## Arguments

| Name    | Type                    | Description                     |
| ------- | ----------------------- | ------------------------------- |
| `input` | `SendCustomEventInput!` | Input data for the custom event |

## Return Type

`SendCustomEventResponse` - Confirmation of the event submission and triggered workflows.

## Input Fields

`SendCustomEventInput`:

| Field       | Type                                                                         | Description                                         |
| ----------- | ---------------------------------------------------------------------------- | --------------------------------------------------- |
| `type`      | `String!`                                                                    | The type/category of the event                      |
| `operation` | `String!`                                                                    | The operation being performed                       |
| `payload`   | [`CustomEventPayloadInput!`](/graphql-api/inputs/customeventpayloadinput.md) | Structured payload with entity ID and optional data |

`CustomEventPayloadInput`:

| Field  | Type  | Description                                        |
| ------ | ----- | -------------------------------------------------- |
| `id`   | `ID!` | The identifier of the entity this event relates to |
| `data` | `Map` | Optional additional data and context information   |

## Return Fields

`SendCustomEventResponse`:

| Field       | Type                   | Description                                  |
| ----------- | ---------------------- | -------------------------------------------- |
| `success`   | `Boolean!`             | Whether the event was successfully submitted |
| `workflows` | `[TemporalWorkflow!]!` | List of workflows triggered by this event    |

The `workflows` field returns [`TemporalWorkflow`](/graphql-api/types/temporalworkflow.md) objects containing:

* `type`: The workflow type name
* `id`: Unique identifier for the workflow instance
* `runID`: Unique identifier for the specific workflow run

## Usage Example

```graphql
mutation {
  sendCustomEvent(
    input: {
      type: "inventory"
      operation: "low_stock_alert"
      payload: {
        id: "item_123456789"
        data: {
          "itemName": "iPhone 13 Pro",
          "currentStock": 5,
          "minimumThreshold": 10,
          "locationId": "warehouse_main",
          "urgency": "high",
          "suggestedReorderQuantity": 50,
          "estimatedRunoutDate": "2024-02-15T10:00:00Z"
        }
      }
    }
  ) {
    success
    workflows {
      type
      id
      runID
    }
  }
}
```

```graphql
mutation {
  # Send customer lifecycle event
  sendCustomEvent(
    input: {
      type: "customer"
      operation: "milestone_reached"
      payload: {
        id: "cust_987654321"
        data: {
          "customerName": "ACME Corp",
          "milestone": "first_anniversary",
          "totalOrderValue": 125000.00,
          "orderCount": 87,
          "loyaltyPoints": 12500,
          "accountManager": "sarah.wilson@company.com",
          "celebrationCampaign": "anniversary_rewards",
          "discountEligible": true
        }
      }
    }
  ) {
    success
    workflows {
      type
      id
      runID
    }
  }
}
```

```graphql
mutation {
  # Send quality control event
  sendCustomEvent(
    input: {
      type: "quality"
      operation: "inspection_failed"
      payload: {
        id: "qc_20240131_001"
        data: {
          "itemId": "item_456789123",
          "batchNumber": "BATCH-2024-015",
          "inspectorId": "user_inspector_01",
          "failureReason": "dimension_out_of_tolerance",
          "measurements": {
            "length": 10.5,
            "expectedLength": 10.0,
            "tolerance": 0.2
          },
          "severity": "major",
          "quarantineRequired": true,
          "supplierNotificationRequired": true
        }
      }
    }
  ) {
    success
    workflows {
      type
      id
      runID
    }
  }
}
```

## Event Types and Operations

### Common Event Types

#### Inventory Events

* **Type**: `"inventory"`
* **Operations**:
  * `"low_stock_alert"` - Stock levels below threshold
  * `"reorder_point_reached"` - Time to reorder inventory
  * `"excess_stock_detected"` - Overstock situation
  * `"item_expired"` - Perishable items approaching expiration

#### Customer Events

* **Type**: `"customer"`
* **Operations**:
  * `"milestone_reached"` - Customer loyalty milestones
  * `"payment_overdue"` - Late payment notifications
  * `"preference_updated"` - Customer preference changes
  * `"complaint_received"` - Customer service issues

#### Order Events

* **Type**: `"order"`
* **Operations**:
  * `"rush_order_received"` - Expedited order processing
  * `"bulk_order_discount"` - Large order special handling
  * `"order_modification"` - Changes to existing orders
  * `"delivery_delay"` - Shipping delays and notifications

#### Quality Events

* **Type**: `"quality"`
* **Operations**:
  * `"inspection_failed"` - Quality control failures
  * `"compliance_violation"` - Regulatory compliance issues
  * `"supplier_rating_changed"` - Supplier performance updates
  * `"recall_initiated"` - Product recall procedures

#### Workflow Events

* **Type**: `"workflow"`
* **Operations**:
  * `"manual_approval_required"` - Human intervention needed
  * `"process_exception"` - Workflow exception handling
  * `"sla_breach"` - Service level agreement violations
  * `"escalation_triggered"` - Process escalation events

## JavaScript Example

```javascript
const SEND_CUSTOM_EVENT = gql`
  mutation SendCustomEvent($input: SendCustomEventInput!) {
    sendCustomEvent(input: $input) {
      success
      workflows {
        type
        id
        runID
      }
    }
  }
`;

// Using the mutation
const [sendCustomEvent] = useMutation(SEND_CUSTOM_EVENT);

const handleLowStockAlert = async (item) => {
  try {
    const { data } = await sendCustomEvent({
      variables: {
        input: {
          type: "inventory",
          operation: "low_stock_alert",
          payload: {
            id: item.id,
            data: {
              itemName: item.name,
              currentStock: item.stockLevel,
              minimumThreshold: item.minThreshold,
              locationId: item.locationId,
              urgency: item.stockLevel <= item.criticalThreshold ? "critical" : "high"
            }
          }
        }
      }
    });

    if (data.sendCustomEvent.success) {
      console.log('Low stock alert sent successfully');

      // Track triggered workflows
      if (data.sendCustomEvent.workflows.length > 0) {
        console.log('Triggered workflows:', data.sendCustomEvent.workflows);
        data.sendCustomEvent.workflows.forEach(workflow => {
          console.log(`Workflow ${workflow.type} started with ID: ${workflow.id}`);
        });
      }
    }
  } catch (error) {
    console.error('Error sending custom event:', error);
  }
};
```

## Event Processing

### Workflow Integration

Custom events can trigger Temporal workflows:

* **Inventory Management**: Automatic reordering workflows
* **Customer Service**: Support ticket creation and routing
* **Quality Control**: Inspection and compliance workflows
* **Notification Systems**: Email, SMS, and push notifications

### External System Integration

Events can be consumed by external systems:

* **ERP Systems**: Business process automation
* **CRM Platforms**: Customer relationship management
* **Analytics Tools**: Business intelligence and reporting
* **Monitoring Systems**: Alerting and dashboard updates

### Event Routing

Events are routed based on:

* **Event Type**: Different handlers for different event categories
* **Operation**: Specific processing logic for each operation
* **Payload Content**: Conditional routing based on event data
* **Tenant Configuration**: Organization-specific event handling

## Payload Guidelines

### Required Fields

While the payload is flexible, consider including:

* **Entity IDs**: Reference to related entities (customer, item, order, etc.)
* **Timestamp**: When the event occurred
* **Source**: System or user that generated the event
* **Priority/Urgency**: Event importance level
* **Context**: Additional information for processing

### Data Types

The payload Map supports:

* **Strings**: Text data and identifiers
* **Numbers**: Quantities, amounts, measurements
* **Booleans**: Flags and status indicators
* **Objects**: Nested data structures
* **Arrays**: Lists of related items

### Best Practices

1. **Consistent Naming**: Use consistent field names across similar events
2. **Complete Context**: Include all necessary information for processing
3. **Avoid Sensitive Data**: Don't include passwords or API keys
4. **Structured Data**: Use nested objects for complex information
5. **Documentation**: Document payload structure for each event type

## Error Handling

Events may fail to process due to:

* **Invalid Type/Operation**: Unknown event type or operation
* **Malformed Payload**: Invalid or missing required data
* **System Overload**: Event queue at capacity
* **Permission Issues**: Insufficient rights to send certain events
* **Configuration Problems**: Event routing or processing configuration errors

## Monitoring and Observability

### Event Tracking

Monitor custom events through:

* **Event Logs**: Detailed logs of all event processing
* **Metrics Dashboards**: Event volume and processing times
* **Error Rates**: Failed event processing statistics
* **Workflow Triggers**: Events that successfully triggered workflows

### Performance Considerations

* **Event Volume**: Monitor event throughput and system capacity
* **Processing Latency**: Time from event submission to processing
* **Queue Depth**: Backlog of pending events
* **Resource Usage**: CPU and memory consumption during event processing

## Breaking Changes

{% hint style="warning" %}
**Breaking Change (2025-01)**: The `SendCustomEventInput.payload` field type has changed from `Map!` to `CustomEventPayloadInput!`.

**Migration required**:

Before:

```graphql
payload: {
  "itemId": "123",
  "itemName": "Widget"
}
```

After:

```graphql
payload: {
  id: "123"
  data: {
    "itemName": "Widget"
  }
}
```

The entity ID must now be provided in the structured `id` field, while additional context data goes in the optional `data` field.
{% endhint %}

{% hint style="info" %}
**New Feature (2025-01)**: The `SendCustomEventResponse` now includes a `workflows` field that returns information about any Temporal workflows triggered by the event. This enables callers to track workflow executions.
{% endhint %}

## Notes

* Events are processed asynchronously - success indicates submission, not completion
* The `workflows` array shows which workflows were triggered by the event
* Event types and operations should be coordinated across teams
* Consider implementing event versioning for backwards compatibility
* Use meaningful, descriptive event types and operations
* Test event processing in development environments before production use


---

# 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
If you need additional information that is not directly available in this page, you can query the documentation 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/graphql-api/mutations/sendcustomevent.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.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
