-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathexecute_order.rb
More file actions
73 lines (58 loc) · 1.72 KB
/
Copy pathexecute_order.rb
File metadata and controls
73 lines (58 loc) · 1.72 KB
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
# frozen_string_literal: true
class ExecuteOrder
delegate :portfolio, :shares, :stock, to: :order, private: true
delegate :price_cents, to: :stock, prefix: true, private: true
def initialize(order)
@order = order
end
def self.execute(...)
new(...).execute
end
def execute
return unless order.pending?
unless valid_order?
cancel_order!
return
end
ActiveRecord::Base.transaction do
create_portfolio_transaction
create_portfolio_stock
update_order_status
end
end
private
attr_accessor :order, :portfolio_stock, :portfolio_transaction
def create_portfolio_transaction
@portfolio_transaction = if order.buy?
portfolio
.portfolio_transactions
.debit
.create!(amount_cents: purchase_cost)
else
portfolio
.portfolio_transactions
.credit
.create!(amount_cents: purchase_cost)
end
end
def create_portfolio_stock
share_amount = order.sell? ? -shares : shares
@portfolio_stock = portfolio
.portfolio_stocks
.create!(stock:, shares: share_amount, purchase_price: stock.current_price)
end
def update_order_status
order.update!(status: :completed, portfolio_stock:, portfolio_transaction:)
end
def purchase_cost
order.purchase_cost
end
def valid_order?
return order.sufficient_funds? if order.buy?
return order.sufficient_shares? if order.sell?
true
end
def cancel_order!
order.cancel!
end
end