I am working on a payment process. Upon a successful payment process, I have to create multiple records. For that, I have made this class:
class DatabaseMaintainer
def initialize(merchant, card, payment_method)
@merchant = merchant
@card = card
@payment_method = payment_method
end
def maintain_records(customer, payment_details, response)
rate = RateCatalog.get_rate(@merchant.id, @card.id, @payment_method.id)
amount = payment_details['total'].to_d
commission = rate.rate * amount / 100
payable = amount - commission
customer.organization_id = @merchant.id
customer.save
cash_transaction = CashTransaction.create!(
amount: amount,
receipt_id: response.authorization,
rate_catalog_id: rate.id,
customer_id: customer.id,
redirect_url: payment_details['redirect_url']
)
Settlement.create!(
commission_amount: commission,
payable_amount: payable,
cash_transaction_id: cash_transaction.id
)
invoice = Invoice.create!(
invoice_number: "#{CommonConstants::INVOICE_NUMBER_PREFIX}#{@merchant.abbreviation}_#{payment_details['invoice_id']}",
total: amount,
status: Invoice.statuses[:paid],
organization_id: @merchant.id,
cash_transaction_id: cash_transaction.id,
description: payment_details['description']
)
item_details = payment_details['items']
item_details.each do |x|
x[:bill_id] = invoice.id
x[:bill_type] = 'Invoice'
end
PurchasedGood.create!(item_details)
end
end
And I am using it as follows:
DatabaseMaintainer.new(@merchant, card_brand, payment_method).maintain_records(@customer, invoice_details, gateway_reply[:message])
Now, even if the code works fine, it clearly is not an optimal design.
I am looking for suggestions to refactor it. Also, is having a class for creating DB records solely justified in my scenario?