~singpolyma/jmp-schemas

b3dca71b41eb8d712379cb1dc8c544e053a7f5ca — Stephen Paul Weber 1 year, 10 months ago 543d618
Function to compute the amount to charge a customer for a given cdr

This takes into account how much of their "included" minute credit has already
been used in the calendar month.
4 files changed, 52 insertions(+), 0 deletions(-)

A deploy/cdr_charge.sql
A revert/cdr_charge.sql
M sqitch.plan
A verify/cdr_charge.sql
A deploy/cdr_charge.sql => deploy/cdr_charge.sql +37 -0
@@ 0,0 1,37 @@
-- Deploy jmp:cdr_charge to pg
-- requires: customer_plans
-- requires: plans
-- requires: cdr_with_charge

BEGIN;

CREATE FUNCTION cdr_charge(
	cdr_start TIMESTAMP,
	cdr_customer_id TEXT,
	cdr_charge NUMERIC -- Basic rate*ceil(billsec/60)
) RETURNS NUMERIC AS $$
WITH unincluded_charge AS (SELECT
	(
		SELECT (plan->'minutes'->'included')::numeric / 10000.0
		FROM plans INNER JOIN customer_plans ON plan_name=plan->>'name'
		WHERE customer_id=cdr_customer_id
	) - (
		SELECT SUM(charge)
		FROM cdr_with_charge
		WHERE
			customer_id=cdr_customer_id AND
			start >= DATE_TRUNC('month', cdr_start) AND
			start <= cdr_start
	)
AS unincluded_charge)

SELECT GREATEST(
	cdr_charge -
		CASE WHEN unincluded_charge < 0
		THEN 0
		ELSE unincluded_charge END,
	0
) FROM unincluded_charge;
$$ LANGUAGE sql;

COMMIT;

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

BEGIN;

DROP FUNCTION cdr_charge;

COMMIT;

M sqitch.plan => sqitch.plan +1 -0
@@ 18,3 18,4 @@ invite_per_15 [transactions invites] 2021-08-18T17:46:38Z Stephen Paul Weber,,, 
call_rates 2021-11-17T01:29:07Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # Table to store per-plan per-direction rates to different prefixes
cdr_with_charge [cdr call_rates customer_plans] 2021-11-17T01:44:14Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # View to get CDR records augmented with rate and charge amount
plans 2021-11-17T18:06:30Z Stephen Paul Weber,,, <singpolyma@singpolyma-beefy> # Table for plan metadata\n\nIdeally this would come from a dhall_fdw, but for now we can import to this.
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

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

BEGIN;

SELECT cdr_charge(localtimestamp, 'abc', 1.12);

ROLLBACK;