Class: Amazon::BuyBoxChangedHandler

Inherits:
ApplicationJob show all
Includes:
RailsEventStore::AsyncHandler
Defined in:
app/subscribers/amazon/buy_box_changed_handler.rb

Overview

Reacts to Events::AmazonBuyBoxChanged seconds after any observer records
the flip — an ANY_OFFER_CHANGED SQS notification, the hourly recovery pull,
or the daily listings pull. On a loss it hands the item to
Catalog::AmazonBuyBoxService, which owns every rule: revert a
probationary raise, or work the signal ladder (Amazon's competitive
threshold, a competing seller offer, a fresh external retailer price) down
to a price that can win the Buy Box back.

This is the whole point of the event: recovery used to wait for the hourly
sweep, which does not run 00:00–06:59 CT, so a Buy Box lost just after
midnight sat untouched until the 06:15 nightly run.

The amount write fires Events::PriceUpdated, so any change propagates to
Amazon through the existing feed-push listener. On a win, nothing to do —
the raising service's stability gate is the natural cooldown.

Idempotent under at-least-once delivery: a revert clears
last_raise_prior_amount/last_raised_at, and the service's own cooldown
(Catalog::AmazonBuyBoxService::LOWERING_COOLDOWN) keeps a burst of offer
notifications from walking the price down repeatedly.

Instance Method Summary collapse

Instance Method Details

#perform(event) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/subscribers/amazon/buy_box_changed_handler.rb', line 29

def perform(event)
  return if event.data[:won]

  catalog_item = CatalogItem.find_by(id: event.data[:catalog_item_id])
  return unless catalog_item

  # #correct, not #call: this event only ever reports a loss, and the
  # decision must not depend on the persisted flag, which an async retry or
  # a later pull may already have flipped back to winning. #correct can
  # only lower or revert, so acting on a stale loss costs nothing; routing
  # through #call could come out the maintenance side and raise a price in
  # response to a loss.
  #
  # No pull needed either: the notification that woke us IS the fresh
  # state, and Buy Box pulls are rate-limited to ~0.5 req/s.
  decision = Catalog::AmazonBuyBoxService.new.correct(catalog_item)

  Rails.logger.info "[Amazon::BuyBoxChangedHandler] Catalog item #{catalog_item.id}: " \
                    "#{decision.action} (#{decision.reason})#{" via #{decision.source}" if decision.source}" \
                    "#{" -> #{decision.price}" if decision.price}"
end