Skip to main content

HandledScript Examples

Explore real-world implementations of HandledScript for e-commerce automation. We provide two types of scripts to handle different automation needs.

Script Types Overview

Client-Facing Scripts

Interactive workflows that customers use directly. These include returns portals, product configurators, and customer service flows.

  • Customer returns & exchanges
  • Product customization flows
  • Order modification portals
  • Self-service support tools

Ruby Scripts

Backend automation scripts that run server-side to handle data processing, integrations, and business logic.

  • Order processing automation
  • Inventory synchronization
  • Shipping & tracking updates
  • Data transformation & routing

Client-Facing Script Example

This comprehensive returns and exchange workflow demonstrates how HandledScript handles complex customer-facing processes with multiple steps, validation, and dynamic UI components.

Key Features:

  • Customer Verification - Order lookup and validation
  • Item Selection - Multi-select with product details
  • Return Reasons - Hierarchical reason categorization
  • Exchange Options - Product variant selection
  • Refund Methods - Multiple payment options
  • Approval Workflows - Manager review when needed
  • Custom UI Components - Rich interactive elements
  • Dynamic Validation - Real-time form validation
returns-exchange-workflow.json
{
"id": 1001,
"name": "Comprehensive Returns & Exchange Workflow",
"description": "Full-featured returns system with customer tiers, eligibility checks, exchange options, refund calculations, and approval workflows",
"finalApiEndpoint": "/HandledWorkflow/{instanceData.create_return_workflow_id}",
"finalApiMethod": "POST",
"instanceData": {
"return_password": "",
"policy_agreement_checkbox": false,
"order_name": "",
"first_name": "",
"last_name": "",
"email": "",
"order_id": "",
"order_number": "",
"phone_number": "",
"line_items": [],
"selected_line_items": [],
"from_address": {},
"total_price": "",
"refund_methods": [
{
"value": "store_credit",
"label": "Store Credit",
"image": "https://media.istockphoto.com/id/1414851698/vector/gift-card-icon.jpg"
},
{
"value": "original_payment_method",
"label": "Original Payment Method",
"image": "https://www.shutterstock.com/image-vector/atm-card-vector-design.jpg"
}
],
"selected_refund_method": [],
"return_type": "",
"return_reason": "",
"exchange_items": [],
"refund_method": "",
"shipping_method": "",
"return_address": {},
"photos": [],
"notes": "",
"refund_amount": 0,
"exchange_amount": 0,
"shipping_cost": 0,
"restocking_fee": 0,
"final_amount": 0,
"requires_approval": false,
"manager_notes": "",
"merchant_return_reasons": [
{"id": "damaged", "name": "Product was damaged", "parent_id": null},
{"id": "no_help", "name": "Didn't help with my ailment", "parent_id": null},
{"id": "fit_issue", "name": "Shoes didn't fit", "parent_id": null},
{"id": "not_expected", "name": "Shoes didn't work as expected", "parent_id": null},
{"id": "wrong_item", "name": "I received the wrong item", "parent_id": null},
{"id": "other", "name": "Other", "parent_id": null, "custom_value": true}
],
"products": [],
"return_address": {
"street": "",
"street2": "",
"city": "",
"country": "",
"postal_code": ""
},
"return_deadline": "",
"pay_to_complete": {
"value": 0,
"currency": "USD"
},
"create_return_workflow_id": "96",
"get_rates_workflow_id": ""
}
}

Ruby Script Example

This Ruby automation script demonstrates server-side processing for creating tracking records from shipping data. It integrates with ShipHero for order fulfillment and Slack for notifications.

Key Features:

  • Time Zone Handling - Configurable timezone support
  • API Integration - ShipHero shipment retrieval
  • Data Processing - Batch shipment handling
  • Error Management - Comprehensive error tracking
  • Database Operations - Tracking record creation
  • Slack Notifications - Automated status updates
  • Logging - Detailed operation logging
  • Fault Tolerance - Graceful failure handling
create_trackings_from_shipments.rb
class CreateTrackingsFromShipments < BaseAutomationService
def execute
@errors = ActiveModel::Errors.new(self)

# Get time zone from variables or default to EST
time_zone = @variables.dig("time_zone") || "America/New_York"

# Setup date range
setup_time_range(time_zone)

# Initialize clients
initialize_clients

# Process shipments
process_shipments
end

private

def setup_time_range(time_zone)
@start_time = if @variables.dig("start_time")
DateTime.parse(@variables.dig("start_time")).in_time_zone(time_zone).strftime("%Y-%m-%dT%H:%M:%S")
elsif @automation_workflow_execution.automation_workflow.last_successful_execution_at
@automation_workflow_execution.automation_workflow.last_successful_execution_at.in_time_zone(time_zone).strftime("%Y-%m-%dT%H:%M:%S")
else
3.days.ago.in_time_zone(time_zone).strftime("%Y-%m-%dT%H:%M:%S")
end

@end_time = if @variables.dig("end_time")
DateTime.parse(@variables.dig("end_time")).in_time_zone(time_zone).strftime("%Y-%m-%dT%H:%M:%S")
else
Time.now.in_time_zone(time_zone).strftime("%Y-%m-%dT%H:%M:%S")
end

Rails.logger.info("Time range determined: #{@start_time} to #{@end_time}")
end

def initialize_clients
@shiphero_client = CommerceAutomationNodes::ShipheroNode.new(credentials: @credentials)
@slack_client = CommerceAutomationNodes::SlackNode.new(credentials: @credentials)

Rails.logger.info("Clients initialized successfully")
end

def process_shipments
# Get shipments from Shiphero
shipments_response = @shiphero_client.get_shipments(
date_from: @start_time,
date_to: @end_time
)&.parsed_body

Rails.logger.info("Shipments retrieved from Shiphero")

# Extract shipments from response
shipments = shipments_response.dig("data", "shipments", "data", "edges")&.map { |edge| edge["node"] } || []

Rails.logger.info("Processing #{shipments.size} shipments")

successful_count = 0
failed_shipments = []

# Process each shipment
shipments.each do |shipment|
begin
process_single_shipment(shipment)
successful_count += 1
rescue => e
Rails.logger.error("Error processing shipment: #{e.message}")
failed_shipments << {
id: shipment.dig("id"),
error: e.message
}
end
end

# Send summary to Slack
send_summary_to_slack(successful_count, failed_shipments, shipments.size)
end

def process_single_shipment(shipment)
created_trackings = []

# Process each shipping label
shipping_labels = shipment.dig("shipping_labels") || []

shipping_labels.each do |label|
Rails.logger.info(label)
# Find or create tracking record for each label
tracking = Tracking.find_or_create_by(tracking_number: label.dig("tracking_number")) do |t|
t.account_id = @automation_workflow_execution.account_id
t.wms_order_id = shipment.dig("order_id")
t.commerce_platform_order_name = shipment.dig("order", "order_number")
t.carrier_id = Carrier.find_by(carrier_code: label.dig("carrier")&.downcase)&.id
t.carrier_service_level = label.dig("shipping_name")
t.notes = "Created via automation on #{Time.now}"
t.fulfillment_center_id = @variables.dig("fulfillment_center_id")
t.tracking_type = "FULFILLMENT_PACKAGE"
end

created_trackings << tracking
Rails.logger.info("Found or created tracking record #{tracking.id} for shipment #{shipment.dig('id')} with tracking number #{label.dig('tracking_number')}")
end

created_trackings
end

def send_summary_to_slack(successful_count, failed_shipments, total_shipments)
message = build_slack_message(successful_count, failed_shipments, total_shipments)

@slack_client.post_message(
channel: @variables.dig("slack_channel").to_s,
text: "Tracking Creation Summary",
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: message
}
}
]
)
end

def build_slack_message(successful_count, failed_shipments, total_shipments)
message = ["*Tracking Creation Summary*
"]
message << "Time Range: #{@start_time} to #{@end_time}"
message << "Total Shipments Processed: #{total_shipments}"
message << "Successfully Created: #{successful_count}"
message << "Failed: #{failed_shipments.size}"

if failed_shipments.any?
message << "
*Failed Shipments:*"
failed_shipments.each do |failure|
message << "• Shipment #{failure[:id]}: #{failure[:error]}"
end
end

message.join("
")
end
end

Need Custom Examples?

Looking for examples specific to your use case? Our team can provide custom script examples tailored to your e-commerce automation needs.