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