drop function if exists ies.schet_insert cascade;
create function ies.schet_insert()
returns trigger as $$
declare 
	_version varchar(5); 
	_next varchar(64);
begin
	
	if (new.type_ = 539 and (new.schetkind = 0 or new.schetkind = 3)) then
	
	call public.sp_generateschetoutnumber(new.schetid, _next);
	 
	_version := 
		case 
			when new.year >= 2025 then '4.1'
			when new.year = 2024 then '4.0'
			when (new.year = 2022 and new.month >= 11) or new.year > 2022 then '3.3'
			when (new.year = 2019 and new.month >= 11) or new.year > 2019 then '3.2'
			when (new.year = 2019 and new.month < 11) then '3.1' 
		end;
	
	update ies.t_schet
    set nschet = _next,
        version = _version
    where schetid = NEW.schetid;
		
	end if;
    return null;
end;
$$ language plpgsql;

drop trigger if exists t_schet_after_insert on ies.t_schet;
create trigger t_schet_after_insert
after insert on ies.t_schet
for each row execute function ies.schet_insert();