reverse transaction with negative amount

This commit is contained in:
Ilion Beyst 2015-09-11 16:34:21 +02:00 committed by Felix Van der Jeugt
parent 020a2b97e8
commit 39ee9a19a2
4 changed files with 11 additions and 15 deletions

View file

@ -12,7 +12,6 @@ class TransactionsQuery
def query def query
Arel::SelectManager.new(ActiveRecord::Base) Arel::SelectManager.new(ActiveRecord::Base)
.from(arel) .from(arel)
.order(@arel_table[:time].desc)
end end
def arel def arel

View file

@ -1,20 +1,20 @@
class TransactionsController < ApplicationController class TransactionsController < ApplicationController
load_and_authorize_resource
skip_before_filter :verify_authenticity_token, only: :create skip_before_filter :verify_authenticity_token, only: :create
before_action :authenticate_user!, except: :create before_action :authenticate_user!, except: :create
before_action :authenticate_user_or_client!, only: :create before_action :authenticate_user_or_client!, only: :create
respond_to :js, only: :create respond_to :js, only: :create
def index
@transactions = Transaction.all
end
def create def create
@transaction = Transaction.new(transaction_params)
@transaction.reverse if @transaction.amount < 0
authorize!(:create, @transaction)
if @transaction.save if @transaction.save
head :created head :created
else else
render json: @transaction.errors.full_messages, status: :unprocessable_entity render json: @transaction.errors.full_messages,
status: :unprocessable_entity
end end
end end

View file

@ -24,13 +24,6 @@ class Transaction < ActiveRecord::Base
validates :amount, numericality: { greater_than: 0 } validates :amount, numericality: { greater_than: 0 }
validate :different_debtor_creditor validate :different_debtor_creditor
def initialize *args, **kwargs
super *args, **kwargs
if amount < 0
self.creditor, self.debtor = debtor, creditor
self.amount = self.amount.abs
end
end
def peer_of(user) def peer_of(user)
return creditor if user == debtor return creditor if user == debtor
@ -42,6 +35,11 @@ class Transaction < ActiveRecord::Base
return amount if user == creditor return amount if user == creditor
end end
def reverse
self.creditor, self.debtor = self.debtor, self.creditor
self.amount *= -1
end
private private
def recalculate_balances def recalculate_balances

View file

@ -35,5 +35,4 @@ RSpec.describe Transaction, type: :model do
expect {trans.save!}.to change {@user.balance}.by(-10) expect {trans.save!}.to change {@user.balance}.by(-10)
end end
end end
end end