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		new(@customer_id, "bonus_for_#{@id}", bonus_amount, "#{@note} bonus")
15	end
16
17	def bonus_amount
18		return BigDecimal(0) if @amount <= 15
19
20		@amount * case @amount
21		when (15..29.99)
22			0.01
23		when (30..139.99)
24			0.03
25		else
26			0.05
27		end
28	end
29
30	def save
31		args = [@customer_id, @id, @amount, @note]
32		DB.exec_params(<<-SQL, args).cmd_tuples.positive?
33			INSERT INTO transactions
34				(customer_id, transaction_id, settled_after, amount, note)
35			VALUES
36				($1, $2, LOCALTIMESTAMP, $3, $4)
37			ON CONFLICT (transaction_id) DO NOTHING
38		SQL
39	end
40end