drop function if exists fw_core.fn_run_trx_post_validation;
CREATE OR REPLACE FUNCTION fw_core.fn_run_trx_post_validation(p_client_id int,p_function_id int,p_job_id int,p_step_id int)
   RETURNS void AS $$
   declare
   	f record;
   	trx_record_count int;
   	w_job_id int := p_job_id;
    w_step_id int := p_step_id;


-- validate Trx data record loading:
   begin

	 for f in select distinct file_syspk from fw_core.fw_jobctl_file_runschedule 
		where latest_runschedule_flag = '1' and end_status != 'error' and end_status_note = 'TRX_completed'
   		loop
    	select count(*) from transactional.test_instance where file_syspk = f.file_syspk into trx_record_count;
    	if (trx_record_count = 0) then
    		--update fw_core.fw_jobctl_runschedule_jobstep set end_status_note = 'trx_post_validation_failed', end_status='success', end_time= now() where job_id = w_job_id and step_id = w_step_id and latest_runschedule_flag = '1';
		update fw_core.fw_jobctl_file_sheet_runschedule set end_status_note = 'trx_post_validation_failed', end_status='error', end_time= now() where file_syspk=f.file_syspk;
		update fw_core.fw_jobctl_file_runschedule set end_status_note = 'trx_post_validation_failed', end_status='error', end_time= now() where file_syspk=f.file_syspk;
    	else
		--update fw_core.fw_jobctl_runschedule_jobstep set end_status_note = 'TRX_completed', end_status='success' , end_time= now() where job_id = w_job_id and step_id = w_step_id and latest_runschedule_flag = '1';
    		update fw_core.fw_jobctl_file_sheet_runschedule set end_status_note = 'TRX_completed', end_status='success', end_time= now() where file_syspk=f.file_syspk;
		update fw_core.fw_jobctl_file_runschedule set end_status_note = 'TRX_completed', end_status='success', end_time= now() where file_syspk=f.file_syspk;
	end if;
    end loop;
update fw_core.fw_jobctl_runschedule_jobstep set end_status='success',  end_status_note = 'TRX_post_validation_completed', end_time= now() where job_id = w_job_id and step_id = w_step_id and latest_runschedule_flag = '1';

end;
$$  LANGUAGE plpgsql;