~singpolyma/jmp-pay

ref: cbbbe757f7ea15fbde1a63a12c775044e55d009e jmp-pay/lib/transaction.rb -rw-r--r-- 1.5 KiB
cbbbe757Stephen Paul Weber Copy in account activation logic from sgx-jmp 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true

require "bigdecimal"

# Largely copied from sgx-jmp to support web activation more properly
# Goes away when web activation goes away
class Transaction
	def self.sale(gateway, **kwargs)
		response = gateway.transaction.sale(**kwargs)
		response.success? ? new(response.transaction) : nil
	end

	attr_reader :amount

	def initialize(braintree_transaction)
		@customer_id = braintree_transaction.customer_details.id
		@transaction_id = braintree_transaction.id
		@created_at = braintree_transaction.created_at
		@amount = BigDecimal(braintree_transaction.amount, 4)
	end

	def insert
		DB.transaction do
			insert_tx
			insert_bonus
		end
		true
	end

	def bonus
		return BigDecimal(0) if amount <= 15
		amount *
			case amount
			when (15..29.99)
				0.01
			when (30..139.99)
				0.03
			else
				0.05
			end
	end

	def to_s
		plus = " + #{'%.4f' % bonus} bonus"
		"$#{'%.2f' % amount}#{plus if bonus.positive?}"
	end

protected

	def insert_tx
		params = [@customer_id, @transaction_id, @created_at, @amount]
		DB.exec(<<~SQL, params)
			INSERT INTO transactions
				(customer_id, transaction_id, created_at, amount, note)
			VALUES
				($1, $2, $3, $4, 'Credit card payment')
		SQL
	end

	def insert_bonus
		return if bonus <= 0
		params = [@customer_id, "bonus_for_#{@transaction_id}", @created_at, bonus]
		DB.exec(<<~SQL, params)
			INSERT INTO transactions
				(customer_id, transaction_id, created_at, amount, note)
			VALUES
				($1, $2, $3, $4, 'Credit card payment bonus')
		SQL
	end
end