transaction.rb

 1# frozen_string_literal: true
 2
 3class Transaction
 4	def initialize(customer_id, id, amount, note)
 5		@customer_id = customer_id
 6		@id = id
 7		@amount = amount
 8		@note = note
 9	end
10
11	def bonus
12		return unless bonus_amount.positive?
13
14		self.class.new(
15			@customer_id,
16			"bonus_for_#{@id}",
17			bonus_amount,
18			"#{@note} bonus"
19		)
20	end
21
22	def bonus_amount
23		return BigDecimal(0) if @amount <= 15
24
25		@amount * case @amount
26		when (15..29.99)
27			0.01
28		when (30..139.99)
29			0.03
30		else
31			0.05
32		end
33	end
34
35	def save
36		args = [@customer_id, @id, @amount, @note]
37		DB.exec_params(<<-SQL, args).cmd_tuples.positive?
38			INSERT INTO transactions
39				(customer_id, transaction_id, settled_after, amount, note)
40			VALUES
41				($1, $2, LOCALTIMESTAMP, $3, $4)
42			ON CONFLICT (transaction_id) DO NOTHING
43		SQL
44	end
45end