forked from fahrPool/fahrPool
70 lines
2.5 KiB
PL/PgSQL
70 lines
2.5 KiB
PL/PgSQL
-- Uebergabeprotokoll per E-Mail an den Ersteller des Auftrags.
|
|
-- Spec: docs/superpowers/specs/2026-10-11-protokoll-email-design.md
|
|
|
|
-- Enqueue beim Wechsel auf 'abgeschlossen'. Die E-Mail wird zum
|
|
-- Abschlusszeitpunkt im Payload festgehalten. Ohne E-Mail keine Zeile.
|
|
-- security definer: liest auth.users und schreibt in die Outbox, beides ohne
|
|
-- Rechte des ausloesenden Nutzers (Fahrer).
|
|
create function public.auftrag_protokoll_enqueue()
|
|
returns trigger
|
|
language plpgsql
|
|
security definer
|
|
set search_path = public
|
|
as $$
|
|
declare
|
|
v_email text;
|
|
begin
|
|
select u.email into v_email from auth.users u where u.id = new.erstellt_von;
|
|
if coalesce(btrim(v_email), '') = '' then
|
|
return new;
|
|
end if;
|
|
|
|
insert into public.notification_outbox (event_type, auftrag_id, payload)
|
|
values (
|
|
'protokoll_abgeschlossen',
|
|
new.id,
|
|
jsonb_build_object('auftragsnummer', new.auftragsnummer, 'empfaenger', v_email)
|
|
);
|
|
return new;
|
|
end;
|
|
$$;
|
|
|
|
create trigger auftrag_protokoll_enqueue_trg
|
|
after update on public.auftraege
|
|
for each row
|
|
when (old.status is distinct from 'abgeschlossen' and new.status = 'abgeschlossen')
|
|
execute function public.auftrag_protokoll_enqueue();
|
|
|
|
-- Claim nur fuer konfigurierte Kanaele: ist ein Kanal nicht konfiguriert,
|
|
-- bleiben seine Zeilen pending statt geclaimt und auf dead gesetzt zu werden.
|
|
-- Ersetzt claim_notification_batch(int) aus 20260903100000_notification_outbox.sql
|
|
-- (einziger Aufrufer: web/lib/notifications/dispatch.ts).
|
|
drop function public.claim_notification_batch(int);
|
|
|
|
create function public.claim_notification_batch(p_limit int, p_event_types text[])
|
|
returns setof public.notification_outbox
|
|
language sql
|
|
security definer
|
|
set search_path = public
|
|
as $$
|
|
update public.notification_outbox o
|
|
set status = 'sending', updated_at = now()
|
|
where o.id in (
|
|
select id from public.notification_outbox
|
|
where event_type = any(p_event_types)
|
|
and (
|
|
(status in ('pending', 'failed') and naechster_versuch_ab <= now())
|
|
or (status = 'sending' and updated_at < now() - interval '15 minutes')
|
|
)
|
|
order by created_at
|
|
limit p_limit
|
|
for update skip locked
|
|
)
|
|
returning o.*;
|
|
$$;
|
|
|
|
revoke all on function public.claim_notification_batch(int, text[]) from public;
|
|
revoke all on function public.claim_notification_batch(int, text[]) from anon;
|
|
revoke all on function public.claim_notification_batch(int, text[]) from authenticated;
|
|
grant execute on function public.claim_notification_batch(int, text[]) to service_role;
|