2022-01-13 00:13:50 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class RepositoryStockValue < ApplicationRecord
|
2022-01-20 19:44:57 +08:00
|
|
|
belongs_to :created_by, class_name: 'User', optional: true, inverse_of: :created_repository_stock_values
|
|
|
|
belongs_to :last_modified_by, class_name: 'User', optional: true, inverse_of: :modified_repository_stock_values
|
2022-01-13 00:13:50 +08:00
|
|
|
has_one :repository_cell, as: :value, dependent: :destroy, inverse_of: :value
|
|
|
|
has_many :repository_ledger_records, dependent: :destroy
|
|
|
|
accepts_nested_attributes_for :repository_cell
|
|
|
|
|
|
|
|
validates :repository_cell, presence: true
|
|
|
|
|
|
|
|
SORTABLE_COLUMN_NAME = 'repository_stock_values.amount'
|
|
|
|
|
|
|
|
def formatted
|
|
|
|
"#{amount} #{units}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def data_changed?(new_data)
|
|
|
|
BigDecimal(new_data.to_s) != data
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_data!(new_data, user)
|
2022-01-20 19:44:57 +08:00
|
|
|
self.amount = BigDecimal(new_data.to_s)
|
2022-01-13 00:13:50 +08:00
|
|
|
self.last_modified_by = user
|
|
|
|
save!
|
|
|
|
end
|
|
|
|
|
|
|
|
def snapshot!(cell_snapshot)
|
|
|
|
value_snapshot = dup
|
|
|
|
value_snapshot.assign_attributes(
|
|
|
|
repository_cell: cell_snapshot,
|
|
|
|
created_at: created_at,
|
|
|
|
updated_at: updated_at
|
|
|
|
)
|
|
|
|
value_snapshot.save!
|
|
|
|
end
|
|
|
|
|
|
|
|
def data
|
|
|
|
amount
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.new_with_payload(payload, attributes)
|
|
|
|
value = new(attributes)
|
|
|
|
value.amount = payload
|
|
|
|
value
|
|
|
|
end
|
|
|
|
|
2022-01-20 19:44:57 +08:00
|
|
|
def update_stock_with_ledger!(amount, reference, comment)
|
2022-01-13 00:13:50 +08:00
|
|
|
delta = amount.to_d - self.amount.to_d
|
2022-01-20 19:44:57 +08:00
|
|
|
repository_ledger_records.create!(
|
|
|
|
user: last_modified_by,
|
|
|
|
amount: delta,
|
|
|
|
balance: amount,
|
|
|
|
reference: reference,
|
|
|
|
comment: comment
|
|
|
|
)
|
2022-01-13 00:13:50 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
alias export_formatted formatted
|
|
|
|
end
|