mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-03-11 03:40:20 +00:00
39 lines
1006 B
Ruby
39 lines
1006 B
Ruby
# frozen_string_literal: true
|
|
|
|
require "spree/localized_number"
|
|
|
|
class CustomerAccountTransaction < ApplicationRecord
|
|
extend Spree::LocalizedNumber
|
|
|
|
localize_number :amount
|
|
|
|
belongs_to :customer
|
|
belongs_to :payment, class_name: "Spree::Payment", optional: true
|
|
belongs_to :created_by, class_name: "Spree::User", optional: true
|
|
|
|
validates :amount, presence: true
|
|
validates :currency, presence: true
|
|
|
|
before_create :update_balance
|
|
|
|
private
|
|
|
|
def readonly?
|
|
!new_record?
|
|
end
|
|
|
|
def update_balance
|
|
# Locking the customer to prevent two transactions from behing created at the same time
|
|
# resulting in a potentially wrong balance calculation.
|
|
customer.with_lock(requires_new: true) do
|
|
last_transaction = CustomerAccountTransaction.where(customer: customer).last
|
|
|
|
self.balance = if last_transaction.present?
|
|
last_transaction.balance + amount
|
|
else
|
|
amount
|
|
end
|
|
end
|
|
end
|
|
end
|