~singpolyma/jmp-pay

dd0f2f2d6221e6bab0aa2a4f44dced8fc1b86c86 — Stephen Paul Weber 1 year, 4 months ago fee70ea
Factor out a transaction object
2 files changed, 44 insertions(+), 17 deletions(-)

M bin/process_pending_btc_transactions
A lib/transaction.rb
M bin/process_pending_btc_transactions => bin/process_pending_btc_transactions +4 -17
@@ 25,6 25,7 @@ require "redis"

require_relative "../lib/blather_notify"
require_relative "../lib/electrum"
require_relative "../lib/transaction"

CONFIG =
	Dhall::Coder


@@ 98,19 99,6 @@ class Plan
		@plan[:currency]
	end

	def bonus_for(fiat_amount)
		return BigDecimal(0) if fiat_amount <= 15

		fiat_amount * case fiat_amount
		when (15..29.99)
			0.01
		when (30..139.99)
			0.03
		else
			0.05
		end
	end

	def price
		BigDecimal(@plan[:monthly_price].to_i) * 0.0001
	end


@@ 184,11 172,10 @@ class Customer
	end

	def add_btc_credit(txid, btc_amount, fiat_amount)
		return unless add_transaction(txid, fiat_amount, "Bitcoin payment")
		tx = Transaction.new(txid, fiat_amount, "Bitcoin payment")
		return unless tx.save

		if (bonus = plan.bonus_for(fiat_amount)).positive?
			add_transaction("bonus_for_#{txid}", bonus, "Bitcoin payment bonus")
		end
		tx.bonus&.save
		notify_btc_credit(txid, btc_amount, fiat_amount, bonus)
	end


A lib/transaction.rb => lib/transaction.rb +40 -0
@@ 0,0 1,40 @@
# frozen_string_literal: true

class Transaction
	def initialize(customer_id, id, amount, note)
		@customer_id = customer_id
		@id = id
		@amount = amount
		@note = note
	end

	def bonus
		return unless bonus_amount.positive?

		new(@customer_id, "bonus_for_#{@id}", bonus_amount, "#{@note} bonus")
	end

	def bonus_amount
		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 save
		args = [@customer_id, @id, @amount, @note]
		DB.exec_params(<<-SQL, args).cmd_tuples.positive?
			INSERT INTO transactions
				(customer_id, transaction_id, settled_after, amount, note)
			VALUES
				($1, $2, LOCALTIMESTAMP, $3, $4)
			ON CONFLICT (transaction_id) DO NOTHING
		SQL
	end
end