1#!/usr/bin/ruby
2# frozen_string_literal: true
3
4# This is meant to be a one-time script that takes any "extra"
5# months an account is activated for and rolls them back into balance instead
6# Mostly as a fix for all the time that web activation spent not setting balance
7
8require "pg"
9
10DB = PG.connect(dbname: "jmp")
11DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
12DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
13
14rows = DB.query(<<~SQL)
15 SELECT customer_id, expires_at,
16 ((((DATE_PART('year', expires_at) - DATE_PART('year', LOCALTIMESTAMP)) * 12 +
17 (DATE_PART('month', expires_at) - DATE_PART('month', LOCALTIMESTAMP))) - 1) *
18 case plan_name
19 when 'usd_beta_unlimited-v20210223' then 2.99
20 when 'cad_beta_unlimited-v20210223' then 3.59
21 end)::NUMERIC(12,4) AS amount
22 FROM customer_plans WHERE expires_at > (DATE_TRUNC('month', LOCALTIMESTAMP) + '2 months') ORDER BY expires_at;
23SQL
24
25rows.each do |r|
26 cid = r["customer_id"]
27 DB.transaction do
28 DB.exec(<<~SQL, [cid, "#{cid}-months_to_balance", r["amount"]])
29 INSERT INTO transactions (customer_id, transaction_id, amount, note)
30 VALUES ($1, $2, $3, 'months_to_balance')
31 SQL
32 DB.exec(<<~SQL, [cid, r["expires_at"]])
33 UPDATE plan_log SET date_range = date_range - tsrange(LOCALTIMESTAMP + '1 month', UPPER(date_range))
34 WHERE customer_id=$1 AND UPPER(date_range)=$2
35 SQL
36 end
37end