Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions app/controllers/transactions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@ def new
end

def create
@transaction = @wallet.transactions.build(transaction_params)

if @transaction.save
respond_to do |format|
format.turbo_stream
format.html { redirect_to transactions_path, notice: "Transaction created successfully!" }
end
else
render :new, status: :unprocessable_entity
@transaction = TransactionService.new(@wallet, transaction_params).execute

respond_to do |format|
format.turbo_stream
format.html { redirect_to @wallet, notice: "Transaction created successfully!" }
end
rescue ActiveRecord::RecordInvalid => e
respond_to do |format|
format.turbo_stream { render turbo_stream: turbo_stream.replace("transaction_form", partial: "form", locals: { transaction: e.record }) }
format.html { render :new, status: :unprocessable_entity }
end
end

Expand Down
44 changes: 44 additions & 0 deletions app/services/transaction_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class TransactionService
def initialize(wallet, transaction_params)
@wallet = wallet
@transaction_params = transaction_params
end

def execute
ActiveRecord::Base.transaction do
@transaction = @wallet.transactions.create!(@transaction_params)
update_holding
@transaction
end
end

private

def update_holding
holding = @wallet.holdings.lock.find_or_initialize_by(instrument_id: @transaction.instrument_id)

if @transaction.buy?
handle_buy(holding)
else
handle_sell(holding)
end

if holding.quantity.zero?
holding.destroy!
else
holding.save!
end
end

def handle_buy(holding)
new_quantity = holding.quantity.to_f + @transaction.quantity
new_total_cost = (holding.quantity.to_f * holding.average_price.to_f) + (@transaction.quantity * @transaction.price)
holding.quantity = new_quantity
holding.average_price = new_total_cost / new_quantity
end

def handle_sell(holding)
raise ActiveRecord::RecordInvalid.new(holding) if holding.quantity < @transaction.quantity
holding.quantity -= @transaction.quantity
end
end