Skip to content

Commit

Permalink
no need to pass line_item when a has_one will do
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorganIO committed Jul 23, 2023
1 parent 568f4ed commit 89d91bd
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions core/app/models/spree/unit_cancel.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ class Spree::UnitCancel < Spree::Base
DEFAULT_REASON = 'Cancel'

belongs_to :inventory_unit, optional: true

has_one :adjustment, as: :source, dependent: :destroy
has_one :line_item, through: :inventory_unit

validates :inventory_unit, presence: true

# Creates necessary cancel adjustments for the line item.
def adjust!
raise "Adjustment is already created" if adjustment

amount = compute_amount(inventory_unit.line_item)
amount = compute_amount

self.adjustment = inventory_unit.line_item.adjustments.create!(
self.adjustment = line_item.adjustments.create!(
source: self,
amount: amount,
order: inventory_unit.order,
Expand All @@ -27,27 +29,29 @@ def adjust!
finalized: true
)

inventory_unit.line_item.order.recalculate
line_item.order.recalculate
adjustment
end

# This method is used by Adjustment#update to recalculate the cost.
def compute_amount(line_item)
raise "Adjustable does not match line item" unless line_item == inventory_unit.line_item

-weighted_line_item_amount(line_item)
def compute_amount
-weighted_amount(line_item.total_before_tax)
end

private

def weighted_line_item_amount(line_item)
quantity_of_line_item = quantity_of_line_item(line_item)
raise ZeroDivisionError, "Line Item does not have any inventory units available to cancel" if quantity_of_line_item.zero?
def weighted_amount(amount)
quantity_of_line_item = quantity_of_line_item

if quantity_of_line_item.zero?
raise ZeroDivisionError,
'Line Item does not have any inventory units available to cancel'
end

line_item.total_before_tax / quantity_of_line_item
amount / quantity_of_line_item
end

def quantity_of_line_item(line_item)
def quantity_of_line_item
BigDecimal(line_item.inventory_units.not_canceled.reject(&:original_return_item).size)
end
end

0 comments on commit 89d91bd

Please sign in to comment.