transaction.rb

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