import { StateSetClient } from 'stateset-node';
const client = new StateSetClient({
apiKey: process.env.STATESET_API_KEY
});
async function createOrderCancellationFunction(agentId) {
try {
const cancelOrderFunction = await client.functions.create({
agent_id: agentId,
name: 'cancel_order',
description: 'Cancels a customer order and processes any necessary refunds',
endpoint: 'https://api.yourstore.com/v1/orders/{order_id}/cancel',
method: 'POST',
parameters: [
{
name: 'order_id',
type: 'string',
description: 'The unique order identifier',
required: true,
validation: {
pattern: '^ORD-[0-9]{6,}$',
example: 'ORD-123456'
}
},
{
name: 'reason',
type: 'string',
description: 'Reason for cancellation',
required: true,
enum: [
'customer_request',
'out_of_stock',
'pricing_error',
'duplicate_order',
'other'
]
},
{
name: 'refund_amount',
type: 'number',
description: 'Amount to refund (if different from order total)',
required: false
}
],
authentication: {
type: 'bearer',
token_env_var: 'STORE_API_TOKEN'
},
headers: {
'Content-Type': 'application/json',
'X-API-Version': '2024-01'
},
request_transform: {
body: {
order_id: '{{order_id}}',
cancellation_reason: '{{reason}}',
refund: {
amount: '{{refund_amount || order_total}}',
method: 'original_payment_method'
},
notify_customer: true
}
},
response_handling: {
success_condition: 'status_code == 200',
error_message_path: 'error.message',
result_mapping: {
success: 'data.cancelled',
order_status: 'data.status',
refund_id: 'data.refund.id',
estimated_refund_date: 'data.refund.estimated_date'
}
},
retry_config: {
max_attempts: 3,
backoff: 'exponential',
retry_on: [502, 503, 504]
},
timeout: 30000, // 30 seconds
rate_limit: {
requests_per_minute: 60
}
});
console.log('Order cancellation function created:', cancelOrderFunction.id);
return cancelOrderFunction;
} catch (error) {
console.error('Failed to create function:', error);
throw error;
}
}