Add bonus whenever a larger BTC deposit comes in

Stephen Paul Weber created

Change summary

bin/process_pending_btc_transactions | 42 ++++++++++++++++++++---------
1 file changed, 29 insertions(+), 13 deletions(-)

Detailed changes

bin/process_pending_btc_transactions 🔗

@@ -79,6 +79,11 @@ class Plan
 	def currency
 		@plan[:currency]
 	end
+
+	def bonus_for(fiat_amount, cad_to_usd)
+		bonus = (0.050167 * fiat_amount) - (currency == :CAD ? 1 : cad_to_usd)
+		return bonus.round(4, :floor) if bonus > 0
+	end
 end
 
 class Customer
@@ -99,23 +104,34 @@ class Customer
 		Plan.for_customer(@customer_id)
 	end
 
-	def add_btc_credit(txid, fiat_amount)
-		DB.exec_params(<<-SQL, [@customer_id, txid, fiat_amount])
+	def add_btc_credit(txid, fiat_amount, cad_to_usd)
+		add_transaction(txid, fiat_amount, "Bitcoin payment")
+		if (bonus = plan.bonus_for(fiat_amount, cad_to_usd))
+			add_transaction("bonus_for_#{txid}", bonus, "Bitcoin payment bonus")
+		end
+		notify_btc_credit(txid, fiat_amount, bonus)
+	end
+
+	def notify_btc_credit(txid, fiat_amount, bonus)
+		tx_hash, = txid.split("/", 2)
+		notify([
+			"Your Bitcoin transaction has been added as ",
+			"$#{'%.4f' % fiat_amount} ",
+			("+ $#{'%.4f' % bonus} bonus " if bonus),
+			"to your account.\n(txhash: #{tx_hash})"
+		].compact.join)
+	end
+
+protected
+
+	def add_transaction(id, amount, note)
+		DB.exec_params(<<-SQL, [@customer_id, id, amount, note])
 			INSERT INTO transactions
 				(customer_id, transaction_id, amount, note)
 			VALUES
-					($1, $2, $3, 'Bitcoin payment')
+					($1, $2, $3, $4)
 			ON CONFLICT (transaction_id) DO NOTHING
 		SQL
-		notify_btc_credit(txid, fiat_amount)
-	end
-
-	def notify_btc_credit(txid, fiat_amount)
-		tx_hash, = txid.split("/", 2)
-		notify(
-			"Your Bitcoin transaction has been added as $#{'%.4f' % fiat_amount} " \
-			"to your account.\n(txhash: #{tx_hash})"
-		)
 	end
 end
 
@@ -133,7 +149,7 @@ REDIS.hgetall("pending_btc_transactions").each do |(txid, customer_id)|
 		plan = customer.plan
 		if plan
 			amount = btc * btc_sell_price.fetch(plan.currency).round(4, :floor)
-			customer.add_btc_credit(txid, amount)
+			customer.add_btc_credit(txid, amount, cad_to_usd)
 		else
 			warn "No plan for #{customer_id} cannot save #{txid}"
 		end