Sha256: 751542df18a72b2529940fa405eb5630558061f7ad4d81510fa029b0a3d2b95a

Contents?: true

Size: 1.7 KB

Versions: 13

Compression:

Stored size: 1.7 KB

Contents

class ReimbursementShipping
  attr_accessor :reimbursement
  attr_reader :order

  include Spree::ReimbursementType::ReimbursementHelpers

  def initialize(reimbursement)
    @order         = reimbursement.order
    @reimbursement = reimbursement
  end

  def update!(shipping_amount)
    reimbursement.update!(total: calculated_amount(shipping_amount))
    create_refund_payment!(shipping_amount)
  end

  private

  def calculate_shipping_amount(shipping_amount)
    [shipping_amount, available_shipment_amount].min
  end

  def calculated_amount(shipping_amount)
    calculate_shipping_amount(shipping_amount) + reimbursement.total
  end

  def available_shipment_amount
    order.shipment_total + order_shipping_tax - refunded_shipping
  end

  def refunded_shipping
    order.refunds.where(refund_reason_id: refund_reason.id).sum(&:amount)
  end

  def create_refund_payment!(shipping_amount)
    create_refunds(reimbursement, payments, calculate_shipping_amount(shipping_amount), false)
  end

  def order_shipping_tax
    order.all_adjustments.where(source_type: 'Spree::TaxRate', adjustable_type: 'Spree::Shipment').sum(&:amount)
  end

  def payments
    reimbursement.order.payments.completed
  end

  def create_refund(reimbursement, payment, amount, simulate)
    refund = reimbursement.refunds.build({
                                           payment: payment,
                                           amount:  amount,
                                           reason:  refund_reason
                                         })

    simulate ? refund.readonly! : refund.save!
    refund
  end

  def refund_reason
    @refund_reason ||= Spree::RefundReason.find_or_create_by!(name: 'Returnly Shipping Refund')
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
spree-returnly-0.13.1 app/models/reimbursement_shipping.rb
solidus-returnly-0.13.1 app/models/reimbursement_shipping.rb
spree-returnly-0.13.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.13.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.12.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.11.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.10.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.9.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.8.1 app/models/reimbursement_shipping.rb
solidus-returnly-0.8.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.7.1 app/models/reimbursement_shipping.rb
solidus-returnly-0.7.0 app/models/reimbursement_shipping.rb
solidus-returnly-0.6.2 app/models/reimbursement_shipping.rb