Class: FlowChat::Whatsapp::Middleware::ChoiceMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/flow_chat/whatsapp/middleware/choice_mapper.rb

Overview

Maps WhatsApp button/list IDs back to original choice keys

Similar to USSD::ChoiceMapper, but for WhatsApp interactive messages. WhatsApp uses generated IDs (from IdGenerator) for buttons and list items, and this middleware maps the user's response back to the original choice key.

Flow:

  1. Flow returns choices with original keys (e.g., => "Create Account")
  2. Middleware generates WhatsApp-safe IDs from labels
  3. Middleware transforms choices to use generated IDs as keys
  4. Middleware stores mapping (generated_id → original_key)
  5. Renderer receives transformed choices and renders them
  6. User selects a button/list item (WhatsApp sends the ID)
  7. This middleware intercepts and replaces ID with original key
  8. Flow sees the original choice key (not the generated ID)

Examples:

# Flow provides: {"create" => "Create Account"}
# Middleware generates ID: "Create Account"
# Middleware transforms to: {"Create Account" => "Create Account"}
# Middleware stores: {"Create Account" => "create"}
# User clicks, WhatsApp sends: "Create Account"
# Middleware intercepts and maps back to: "create"

# With duplicates: {"yes" => "Accept", "no" => "Accept"}
# IDs generated: "Accept", "Accept 3a4"
# Transformed: {"Accept" => "Accept", "Accept 3a4" => "Accept"}
# Mapping: {"Accept" => "yes", "Accept 3a4" => "no"}
# User clicks second, WhatsApp sends: "Accept 3a4"
# Middleware maps back to: "no"

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ChoiceMapper

Returns a new instance of ChoiceMapper.



38
39
40
41
# File 'lib/flow_chat/whatsapp/middleware/choice_mapper.rb', line 38

def initialize(app)
  @app = app
  FlowChat.logger.debug { "Whatsapp::ChoiceMapper: Initialized WhatsApp choice mapping middleware" }
end

Instance Method Details

#call(context) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/flow_chat/whatsapp/middleware/choice_mapper.rb', line 43

def call(context)
  @context = context
  @session = context.session

  session_id = context["session.id"]
  FlowChat.logger.debug { "Whatsapp::ChoiceMapper: Processing request for session #{session_id}" }

  if intercept?
    FlowChat.logger.info { "Whatsapp::ChoiceMapper: Intercepting request for choice resolution - session #{session_id}" }
    handle_choice_input
  end

  # Clear choice mapping state for new flows
  clear_choice_state_if_needed

  # Call the app (executor -> flow)
  type, prompt, choices, media = @app.call(context)

  # Transform choices if present (like USSD does)
  if choices.present?
    FlowChat.logger.debug { "Whatsapp::ChoiceMapper: Found choices, creating ID mapping" }
    choices = create_id_mapping(choices)
  end

  [type, prompt, choices, media]
end