module Solidus module Returnly class Refunds attr_accessor :calculator, :order, :line_items, :restock, :transactions def initialize(order:, line_items:, restock: true, transactions:) self.order = order self.line_items = line_items self.calculator = Calculator.new order, line_items self.restock = restock self.transactions = transactions end def restock_return(customer_return) customer_return.return_items.each do |item| customer_return.stock_location.restock(item.inventory_unit.variant, 1, customer_return) end end def proceed! customer_return = Spree::CustomerReturn.new customer_return_params customer_return.return_items = calculator.line_items_return_items.values.flatten customer_return.return_items.each do |return_item| return_item.amount = refund_amount_per_item return_item.resellable = self.restock end if customer_return.save! reimbursement = perform_reimbursement(customer_return) processed_customer_return(customer_return, reimbursement) end end def processed_customer_return(customer_return, reimbursement) { refund_id: customer_return.number, created_at: customer_return.created_at, updated_at: customer_return.updated_at, line_items: customer_return.return_items.map {|ri| { refund_line_item_id: ri.id, order_line_item_id: ri.inventory_unit.line_item.id, quantity: 1 } }, transactions: [ id: reimbursement.id, amount: reimbursement.total ], note: "comment text", restock: true } end def perform_reimbursement(customer_return) reimbursement = Spree::Reimbursement.build_from_customer_return(customer_return) reimbursement.save! reimbursement.perform! reimbursement end def customer_return_params { stock_location_id: stock_location_id, } end def stock_location_id order.shipments.last.stock_location.id end def refund_available_amount @available_amount ||= self.transactions.sum {|t| Money.from_amount(t[:amount].to_f)} end def refund_amount_per_item refund_available_amount / line_items.size end end end end