mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-03 22:06:07 +00:00
This new class lets us [Branch by abstraction](https://www.martinfowler.com/bliki/BranchByAbstraction.html) by encapsulating an order's balance. As a result, that's the only place where we need to check the feature toggle, instead of every place where `#outstanding_balance` is called (quite some). That would be very hard to review and it'd be more likely to introduce bugs. What I like about this is that we also managed to group together the data and logic that we had spread in a few places and have it nicely encapsulated. So, where we had a number, we'll now have an object. Once we fully change all `#outstanding_balance` consumers to use this new abstraction we'll be able to remove the methods this class replaces. These are: `Spree::Order#outstanding_balance?`, `Spree::Order#display_oustanding_balance` and `OrderHelper.outstanding_balance_label`. This is just the first step. I'll follow this up with a PR per page/mailer/whatever where we use the balance to replace it with an instance of `OrderBalance`. That is, splitting up what I explored in https://github.com/openfoodfoundation/openfoodnetwork/pull/6959 but in very small and manageable pieces.
34 lines
573 B
Ruby
34 lines
573 B
Ruby
# frozen_string_literal: true
|
|
|
|
class OrderBalance
|
|
def initialize(order)
|
|
@order = order
|
|
end
|
|
|
|
def label
|
|
to_f.negative? ? I18n.t(:credit_owed) : I18n.t(:balance_due)
|
|
end
|
|
|
|
def amount
|
|
Spree::Money.new(to_f, currency: order.currency)
|
|
end
|
|
|
|
def to_f
|
|
if customer_balance_enabled?
|
|
order.new_outstanding_balance
|
|
else
|
|
order.outstanding_balance
|
|
end
|
|
end
|
|
|
|
delegate :zero?, to: :to_f
|
|
|
|
private
|
|
|
|
attr_reader :order
|
|
|
|
def customer_balance_enabled?
|
|
OpenFoodNetwork::FeatureToggle.enabled?(:customer_balance, order.user)
|
|
end
|
|
end
|