1# frozen_string_literal: true
2
3require "bigdecimal"
4
5# Largely copied from sgx-jmp to support web activation more properly
6# Goes away when web activation goes away
7class Transaction
8 def self.sale(gateway, **kwargs)
9 response = gateway.transaction.sale(**kwargs)
10 response.success? ? new(response.transaction) : nil
11 end
12
13 attr_reader :amount
14
15 def initialize(braintree_transaction)
16 @customer_id = braintree_transaction.customer_details.id
17 @transaction_id = braintree_transaction.id
18 @created_at = braintree_transaction.created_at
19 @amount = BigDecimal(braintree_transaction.amount, 4)
20 end
21
22 def insert
23 DB.transaction do
24 insert_tx
25 insert_bonus
26 end
27 true
28 end
29
30 def bonus
31 return BigDecimal(0) if amount <= 15
32
33 amount *
34 case amount
35 when (15..29.99)
36 0.01
37 when (30..139.99)
38 0.03
39 else
40 0.05
41 end
42 end
43
44 def to_s
45 plus = " + #{'%.4f' % bonus} bonus"
46 "$#{'%.2f' % amount}#{plus if bonus.positive?}"
47 end
48
49protected
50
51 def insert_tx
52 params = [@customer_id, @transaction_id, @created_at, @amount]
53 DB.exec(<<~SQL, params)
54 INSERT INTO transactions
55 (customer_id, transaction_id, created_at, amount, note)
56 VALUES
57 ($1, $2, $3, $4, 'Credit card payment')
58 SQL
59 end
60
61 def insert_bonus
62 return if bonus <= 0
63
64 params = [
65 @customer_id, "bonus_for_#{@transaction_id}",
66 @created_at, bonus
67 ]
68 DB.exec(<<~SQL, params)
69 INSERT INTO transactions
70 (customer_id, transaction_id, created_at, amount, note)
71 VALUES
72 ($1, $2, $3, $4, 'Credit card payment bonus')
73 SQL
74 end
75end