create or replace function billing.receipt_issue(p_reading billing.reading, p_key text) returns jsonb language plpgsql as $$ declare v_tariff jsonb; v_quantity numeric; v_rate numeric(12, 2); v_total numeric(22, 2); v_id bigint; begin select item -> 'tariff' into v_tariff from jsonb_array_elements(billing.resource_types()) item where item ->> 'id' = p_reading.kind; v_quantity := (p_reading.metrics ->> (v_tariff ->> 'metric'))::numeric; v_rate := (v_tariff ->> 'rate')::numeric; v_total := round(v_quantity * v_rate, 2); insert into billing.receipt (reading_id, key_digest, data) values (p_reading.id, digest(p_key, 'sha256'), jsonb_build_object( 'reading', jsonb_build_object('id', p_reading.id, 'serial', p_reading.serial, 'kind', p_reading.kind, 'metrics', p_reading.metrics, 'created_at', p_reading.created_at, 'parameters', p_reading.parameters), 'calculation', jsonb_build_object('metric', v_tariff ->> 'metric', 'quantity', v_quantity, 'unit', v_tariff ->> 'unit', 'unit_price', v_rate::text, 'amount', v_total::text, 'currency', 'EDD', 'formula', 'quantity * unit_price') )) returning id into v_id; return jsonb_build_object('receipt_id', v_id); end; $$; create or replace function billing.receipt_list() returns jsonb language sql stable as $$ select coalesce(jsonb_agg(jsonb_build_object('id', id, 'created_at', created_at) order by created_at desc, id desc), '[]'::jsonb) from billing.receipt $$; create or replace function billing.receipt_open(p_id bigint, p_key text) returns jsonb language plpgsql stable as $$ declare v_receipt billing.receipt; begin select c.* into v_receipt from billing.receipt c join billing.reading r on r.id = c.reading_id where c.id = p_id and r.created_at > now() - interval '10 minutes'; if not found or p_key is null or digest(p_key, 'sha256') is distinct from v_receipt.key_digest then raise exception 'Receipt unavailable. Check the receipt ID and calculation ID.' using errcode = 'P0403'; end if; return jsonb_build_object('id', v_receipt.id, 'reading_id', v_receipt.reading_id, 'created_at', v_receipt.created_at) || v_receipt.data; end; $$;