Files
openfoodnetwork/app/models/concerns/balance.rb
Pau Perez 5815d1a4a4 Make #outstanding_balance return an OrderBalance
This will let us branch by abstraction. All existing calls to
`#outstanding_balance` will go through `OrderBalance` hence, will
check the feature toggle.

Note that by default, `OrderBalance` will end up calling
`#old_outstanding_balance`. As the name states, that's exactly what
`#outstanding_balance` was so far. This means no consumers will see any
change in behavior. We just added on item in the call stack (sort of).
2021-03-22 11:45:12 +01:00

48 lines
1.6 KiB
Ruby

# frozen_string_literal: true
require 'active_support/concern'
# Contains the methods to compute an order balance form the point of view of the enterprise and not
# the individual shopper.
module Balance
FINALIZED_NON_SUCCESSFUL_STATES = %w(canceled returned).freeze
# Branches by the OrderBalance abstraction
def outstanding_balance
OrderBalance.new(self)
end
# This method is the one we're gradually replacing with `#new_outstanding_balance`. Having them
# separate enables us to choose which implementation we want depending on the context using
# a feature toggle. This avoids inconsistent behavior during that incremental refactoring.
#
# It is meant to be removed as soon as we get product approval that the new implementation has
# been working correctly in production.
def old_outstanding_balance
total - payment_total
end
# Returns the order balance by considering the total as money owed to the order distributor aka.
# the shop, and as a positive balance of said enterprise. If the customer pays it all, the
# distributor and customer are even.
#
# Note however, this is meant to be used only in the context of a single order object. When
# working with a collection of orders, such an index controller action, please consider using
# `app/queries/outstanding_balance.rb` instead so we avoid potential N+1s.
def new_outstanding_balance
if state.in?(FINALIZED_NON_SUCCESSFUL_STATES)
-payment_total
else
total - payment_total
end
end
def outstanding_balance?
!outstanding_balance.zero?
end
def display_outstanding_balance
outstanding_balance.amount
end
end