This repository has been archived by the owner on Feb 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
abandoned_carts_endpoint.rb
84 lines (68 loc) · 2.55 KB
/
abandoned_carts_endpoint.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
Dir['./lib/**/*.rb'].each(&method(:require))
class AbandonedCartsEndpoint < EndpointBase::Sinatra::Base
set :logging, true
Honeybadger.configure do |config|
config.api_key = ENV['HONEYBADGER_KEY']
config.environment_name = ENV['RACK_ENV']
end
Mongoid.load!("./config/mongoid.yml")
post '/add_cart' do
cart = Cart.find_or_initialize_by(number: cart_hash['number'] || cart_hash['id'])
cart.attributes = {
payload: payload_without_parameters,
last_activity_at: cart_hash['updated_at'],
# Even though a cart might have been abandoned,
# if there's any activity on it - make it active again
abandoned_at: nil
}
if cart.save
result 200, "Successfully created a cart with the order number #{cart.number}"
else
result 500, cart.error_notification
end
end
post '/update_cart' do
cart = Cart.find_or_initialize_by(number: cart_hash['number'] || cart_hash['id'])
cart.attributes = {
payload: payload_without_parameters,
last_activity_at: cart_hash['updated_at'],
# Even though a cart might have been abandoned,
# if there's any activity on it - make it active again
abandoned_at: nil
}
if cart.save
result 200, "Successfully updated a cart with the order number #{cart.number}"
else
result 500, cart.error_notification
end
end
post '/match_cart' do
## Would we still destroy a cart that has already been abandoned?
## Or we should add :abandoned_at => nil to the .where clause to keep them?
if Cart.where(number: order_hash['number'] || order_hash['id']).destroy > 0
result 200, "Successfully matched the new order to the cart"
else
result 500, "Error: Unable to match the new order to a cart"
end
end
post '/poll' do
abandoned_carts = Cart.abandoned(abandonment_period_hours).each do |cart|
add_object :cart, cart.payload
end
abandoned_carts.update_all(abandoned_at: Time.now.utc)
result 200, "#{abandoned_carts.count} abandoned carts found"
end
private
def payload_without_parameters
@payload.tap {|x| x.delete(:parameters)}
end
def cart_hash
@payload['cart'] or raise InvalidParameters, "'cart' hash must be present in the payload"
end
def order_hash
@payload['order'] or raise InvalidParameters, "'order' hash must be present in the payload"
end
def abandonment_period_hours
@config['abandoned_carts_abandonment_period_hours'] or raise InvalidParameters, "'abandonment_period_hours' parameter must be passed in"
end
end