| 1 | DROP PROCEDURE IF EXISTS public.proc_record_payment(bigint, bigint, bigint, numeric, text);
|
|---|
| 2 |
|
|---|
| 3 | CREATE PROCEDURE public.proc_record_payment(
|
|---|
| 4 | p_account_id bigint,
|
|---|
| 5 | p_invoice_id bigint,
|
|---|
| 6 | p_payment_method_id bigint,
|
|---|
| 7 | p_amount numeric,
|
|---|
| 8 | p_reference_number text DEFAULT NULL
|
|---|
| 9 | )
|
|---|
| 10 | LANGUAGE plpgsql
|
|---|
| 11 | AS $$
|
|---|
| 12 | DECLARE
|
|---|
| 13 | v_payment_id bigint;
|
|---|
| 14 | BEGIN
|
|---|
| 15 | IF p_amount <= 0 THEN
|
|---|
| 16 | RAISE EXCEPTION 'Payment amount must be positive.';
|
|---|
| 17 | END IF;
|
|---|
| 18 | IF NOT EXISTS (
|
|---|
| 19 | SELECT 1 FROM public.invoices
|
|---|
| 20 | WHERE invoice_id = p_invoice_id AND account_id = p_account_id AND status <> 'cancelled'
|
|---|
| 21 | ) THEN
|
|---|
| 22 | RAISE EXCEPTION 'Invoice % is invalid for account %.', p_invoice_id, p_account_id;
|
|---|
| 23 | END IF;
|
|---|
| 24 | IF NOT EXISTS (
|
|---|
| 25 | SELECT 1 FROM public.payment_methods
|
|---|
| 26 | WHERE payment_method_id = p_payment_method_id AND status = 'active'
|
|---|
| 27 | ) THEN
|
|---|
| 28 | RAISE EXCEPTION 'Payment method % is not active.', p_payment_method_id;
|
|---|
| 29 | END IF;
|
|---|
| 30 |
|
|---|
| 31 | INSERT INTO public.payments (
|
|---|
| 32 | account_id, invoice_id, payment_method_id, payment_date,
|
|---|
| 33 | amount, reference_number, status
|
|---|
| 34 | ) VALUES (
|
|---|
| 35 | p_account_id, p_invoice_id, p_payment_method_id, CURRENT_TIMESTAMP,
|
|---|
| 36 | p_amount, p_reference_number, 'completed'
|
|---|
| 37 | ) RETURNING payment_id INTO v_payment_id;
|
|---|
| 38 |
|
|---|
| 39 | RAISE NOTICE 'Payment % recorded successfully.', v_payment_id;
|
|---|
| 40 | END;
|
|---|
| 41 | $$;
|
|---|