diff --git a/app/models/bank_transaction.rb b/app/models/bank_transaction.rb index f53a286ba..51895ae5e 100644 --- a/app/models/bank_transaction.rb +++ b/app/models/bank_transaction.rb @@ -31,12 +31,18 @@ class BankTransaction < ApplicationRecord @registrar ||= Invoice.find_by(reference_no: parsed_ref_number)&.buyer end + def autobindable? + return false if binded? + return false unless registrar + return false unless invoice + return false unless invoice.payable? + + true + end + # For successful binding, reference number, invoice id and sum must match with the invoice def autobind_invoice(manual: false) - return if binded? - return unless registrar - return unless invoice - return unless invoice.payable? + return unless autobindable? channel = if manual 'admin_payment' diff --git a/app/models/invoice.rb b/app/models/invoice.rb index a130a90ff..28fd60f00 100644 --- a/app/models/invoice.rb +++ b/app/models/invoice.rb @@ -112,6 +112,15 @@ class Invoice < ApplicationRecord e_invoice_sent_at.present? end + def self.create_from_transaction!(transaction) + registrar_user = Registrar.find_by(reference_no: transasction.parsed_ref_number) + return unless registrar_user + + registrar_user.issue_prepayment_invoice(amount: transaction.sum, + description: 'Direct top-up via bank transfer', + paid: true) + end + private def apply_default_buyer_vat_no diff --git a/app/models/registrar.rb b/app/models/registrar.rb index 470d768b7..25380b4ef 100644 --- a/app/models/registrar.rb +++ b/app/models/registrar.rb @@ -54,7 +54,7 @@ class Registrar < ApplicationRecord end end - def issue_prepayment_invoice(amount, description = nil) + def issue_prepayment_invoice(amount, description = nil, paid: false) vat_rate = ::Invoice::VatRateCalculator.new(registrar: self).calculate invoice = invoices.create!( @@ -99,7 +99,7 @@ class Registrar < ApplicationRecord } ] ) - SendEInvoiceJob.enqueue(invoice.id) + SendEInvoiceJob.enqueue(invoice.id) unless paid invoice end diff --git a/lib/tasks/invoices/process_payments.rake b/lib/tasks/invoices/process_payments.rake index 340aba187..3e02a8838 100644 --- a/lib/tasks/invoices/process_payments.rake +++ b/lib/tasks/invoices/process_payments.rake @@ -36,6 +36,8 @@ namespace :invoices do reference_no: incoming_transaction.payment_reference_number, description: incoming_transaction.payment_description } transaction = bank_statement.bank_transactions.create!(transaction_attributes) + Invoice.create_from_transaction!(transaction) unless transaction.autobindable? + transaction.autobind_invoice end end