Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-18 01:06:47 +00:00
co-authored by renee-png
parent 20ce4f89e3
commit a6213785ea
2 changed files with 151 additions and 0 deletions
@@ -0,0 +1,64 @@
ALTER TABLE public.invoices ADD COLUMN IF NOT EXISTS is_retainer boolean NOT NULL DEFAULT false;
CREATE TABLE IF NOT EXISTS public.trust_ledger_entries (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
client_id uuid NOT NULL REFERENCES public.clients(id) ON DELETE CASCADE,
entry_date date NOT NULL DEFAULT CURRENT_DATE,
entry_type text NOT NULL CHECK (entry_type IN ('deposit', 'withdrawal')),
amount numeric NOT NULL CHECK (amount >= 0),
note text,
source_invoice_id uuid REFERENCES public.invoices(id) ON DELETE SET NULL,
applied_invoice_id uuid REFERENCES public.invoices(id) ON DELETE SET NULL,
source_payment_id uuid REFERENCES public.invoice_payments(id) ON DELETE SET NULL,
applied_payment_id uuid REFERENCES public.invoice_payments(id) ON DELETE SET NULL,
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS trust_ledger_client_idx ON public.trust_ledger_entries(client_id, entry_date DESC);
ALTER TABLE public.trust_ledger_entries ENABLE ROW LEVEL SECURITY;
CREATE POLICY trust_ledger_select ON public.trust_ledger_entries
FOR SELECT TO authenticated USING (true);
CREATE POLICY trust_ledger_insert ON public.trust_ledger_entries
FOR INSERT TO authenticated WITH CHECK (auth.uid() IS NOT NULL);
CREATE POLICY trust_ledger_delete ON public.trust_ledger_entries
FOR DELETE TO authenticated USING (public.is_admin(auth.uid()) OR created_by = auth.uid());
CREATE TRIGGER trust_ledger_set_updated_at
BEFORE UPDATE ON public.trust_ledger_entries
FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();
CREATE OR REPLACE FUNCTION public.tg_trust_deposit_from_payment()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_client_id uuid;
v_is_retainer boolean;
BEGIN
SELECT i.client_id, i.is_retainer INTO v_client_id, v_is_retainer
FROM public.invoices i WHERE i.id = NEW.invoice_id;
IF v_is_retainer IS TRUE AND v_client_id IS NOT NULL AND NEW.amount > 0 THEN
INSERT INTO public.trust_ledger_entries
(client_id, entry_date, entry_type, amount, note, source_invoice_id, source_payment_id, created_by)
VALUES
(v_client_id, NEW.paid_on, 'deposit', NEW.amount,
'Retainer payment', NEW.invoice_id, NEW.id, NEW.created_by);
END IF;
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trust_deposit_from_payment ON public.invoice_payments;
CREATE TRIGGER trust_deposit_from_payment
AFTER INSERT ON public.invoice_payments
FOR EACH ROW EXECUTE FUNCTION public.tg_trust_deposit_from_payment();