Files
mc_cars_gmbh_infraestructure/supabase/migrations/15-individuell-vat-subtotal-fix.sql
T
Lago f46ba8cadc feat(i18n): add VAT labels and email sent messages in German and English
style(admin): increase max-width of admin page and adjust table styles

fix(n8n): enhance workflow import and publishing process

fix(workflows): update SQL queries for fetching and updating sales orders

feat(migrations): normalize rental types and enhance email guard for individuell rentals

feat(migrations): add RPC for updating deposit in sales orders

fix(migrations): ensure individuell orders persist net/vat components and backfill existing records

test: update last run status to failed
2026-05-17 22:35:11 +02:00

62 lines
1.9 KiB
PL/PgSQL

-- Ensure individuell orders persist net/vat components when total is manually set
-- and backfill existing records where these fields are still zero.
create or replace function public.sales_order_set_total(p_so_id uuid, p_total_eur integer)
returns void
language plpgsql
security invoker
as $$
declare
v_so public.sales_orders;
v_subtotal_eur integer := 0;
v_vat_eur integer := 0;
begin
select * into v_so from public.sales_orders where id = p_so_id for update;
if not found then
raise exception 'sales order % not found', p_so_id;
end if;
if v_so.rental_type != 'individuell' then
raise exception 'can only set total for individuell orders';
end if;
if coalesce(p_total_eur, 0) < 0 then
raise exception 'total must be >= 0';
end if;
if p_total_eur > 0 then
v_subtotal_eur := round(p_total_eur / 1.2);
v_vat_eur := p_total_eur - v_subtotal_eur;
end if;
update public.sales_orders
set total_eur = p_total_eur,
subtotal_eur = v_subtotal_eur,
vat_eur = v_vat_eur,
daily_subtotal = v_subtotal_eur,
weekend_subtotal = 0,
weekday_count = coalesce(total_days, 0),
weekend_day_count = 0,
updated_at = now()
where id = p_so_id;
end;
$$;
grant execute on function public.sales_order_set_total(uuid, integer) to authenticated;
-- Backfill already existing individuell orders with missing net/vat split.
update public.sales_orders
set subtotal_eur = round(total_eur / 1.2),
vat_eur = total_eur - round(total_eur / 1.2),
daily_subtotal = round(total_eur / 1.2),
weekend_subtotal = 0,
weekday_count = coalesce(total_days, 0),
weekend_day_count = 0,
updated_at = now()
where rental_type = 'individuell'
and coalesce(total_eur, 0) > 0
and coalesce(subtotal_eur, 0) = 0
and coalesce(vat_eur, 0) = 0;
notify pgrst, 'reload schema';