~singpolyma/jmp-schemas

240b3444466fb458b517d84c83bd6a782a21934e — Stephen Paul Weber 9 months ago c9889dc
NOTIFY on low balance

This will be picked up by the LISTEN in sgx-jmp to auto-top-up or notify the
customer of low balance.
A deploy/notify_low_balance.sql => deploy/notify_low_balance.sql +25 -0
@@ 0,0 1,25 @@
-- Deploy jmp:notify_low_balance to pg
-- requires: transactions
-- requires: balances

BEGIN;

CREATE OR REPLACE FUNCTION check_and_notify_low_balance() RETURNS TRIGGER AS $$
	DECLARE
		bal NUMERIC;
	BEGIN
		SELECT balance INTO bal FROM balances WHERE customer_id = NEW.customer_id;
		IF bal < 5 THEN
			SELECT pg_notify('low_balance', NEW.customer_id);
		END IF;
		RETURN NEW;
	END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER notify_low_balance
	AFTER INSERT ON transactions
	FOR EACH ROW
	WHEN (NEW.amount < 0)
	EXECUTE PROCEDURE check_and_notify_low_balance();

COMMIT;

A revert/notify_low_balance.sql => revert/notify_low_balance.sql +8 -0
@@ 0,0 1,8 @@
-- Revert jmp:notify_low_balance from pg

BEGIN;

DROP TRIGGER notify_low_balance ON transactions;
DROP FUNCTION check_and_notify_low_balance;

COMMIT;

M sqitch.plan => sqitch.plan +1 -0
@@ 21,3 21,4 @@ plans 2021-11-17T18:06:30Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> #
customers 2021-11-30T16:36:48Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # Get customers from Redis\n\nRequires a redis_server to be configured on the postgres instance.
cdr_charge [customer_plans plans cdr_with_charge] 2021-11-17T18:09:49Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # Get the amount to charge a customer for a given CDR
insert_charge_for_cdr [cdr_charge cdr_with_charge transactions] 2021-11-23T14:41:15Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # Trigger to insert a transaction for the charge for this CDR
notify_low_balance [transactions balances] 2021-12-22T00:36:03Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # NOTIFY when balance dips low

A verify/notify_low_balance.sql => verify/notify_low_balance.sql +7 -0
@@ 0,0 1,7 @@
-- Verify jmp:notify_low_balance on pg

BEGIN;

-- Cannot LISTEN from inside DB

ROLLBACK;